Reputation: 217
I am having an issue that I can't seem to solve! Specifically with the TrimEnd() function.
Background: Using Visual Studio 2010 Express, I'm building a VB.NET application that pulls data from a built-in SQL Database using LINQ to SQL and puts it into a datagrid view. I'm then taking a value from a the datagrid and putting it into a variable somewhere else.
Problem: If a field in the database has a maximum length of say 25 characters, but this one specifically is only 10, I'm getting 15 extra spaces at the end it. So when I pull the cell value into a variable, it's "variable "
.
I've been trying to get rid of the spaces at the end. The only method that works is the .Replace
method, but I don't want to get rid of any spaces that are in the middle, only the extra at the end. Here's some stuff that I've tried after doing some research:
1.
Dim sChar as String = " "
myVariable = myVariable.TrimEnd(sChar)
2.
myVariable = myVariable.Trim()
3.
Dim charsToTrim As Char() = {" "c}
myVariable = myVariable.TrimEnd(charsToTrim)
None of these have worked. As I said the myVariable = myVariable.Replace(" ", "") works, but I don't want to get rid of ALL the spaces, just the ones on the end and Trim isn't working. If anyone has any ideas I'd like to hear them.
Update Resolution Steps:
So it was suggested to update the columns to nvarchar. This allows me to enter data into a field and SQL not filling up the left over characters with extra spaces. However once I made that change my LINQ to SQL stopped working.
Public Sub LoadClients()
Dim query = From a In db.Clients
Select a.Account_Number,
a.Client_Type,
a.Client_Name,
a.Client_Address1,
a.Client_Address2,
a.Client_City,
a.Client_State,
a.Client_ZIP,
a.Client_Contact,
a.Client_Phone
dgvClients.DataSource = query
Getting InvalidCastException was unhandled - Specific cast is not valid.
Upvotes: 0
Views: 6586
Reputation: 460098
The code you have posted should work, especially this:
myVariable = myVariable.TrimEnd() ' note the missing parameters
It will remove all white-spaces from the end which includes even tab characters or line breaks.
So I assume that the problem is the type of the column. If it's char
or nchar
it will always have a length of 25 even if it's shorter. Use varchar
or nvarchar
then.
See Stack Overflow question What is the difference between char, nchar, varchar, and nvarchar in SQL Server?
Upvotes: 1