I have a small function that creates a .csv file from strings stored in a Data Grid.
Dim rowcount As Integer = DataGridView1.Rows.Count - 1
For m As Integer = 0 To rowcount
Dim strrowvalue As String = ""
strrowvalue += CStr(DataGridView1.Rows(m).Cells(0).Value)
For n As Integer = 1 To DataGridView1.Columns.Count - 1
If DataGridView1.CurrentCell.Value Is DBNull.Value Then
strrowvalue += "," + "0"
End If
If DataGridView1.Rows(m).Cells(n).Value Is DBNull.Value Then
strrowvalue += "," + "0"
Else
strrowvalue += "," + CStr(DataGridView1.Rows(m).Cells(n).Value)
End If
Next
If m <> rowcount Then
streamwriter.WriteLine(strrowvalue)
End If
Next
However after the first value a linebreak is inserted. This causes Excel and other programs to place the first value on line 1, then the rest of the values of that line are placed on line 2.
Example:
-
100 ,
-
555,333,333,666,777
-
200 ,
-
444,555,453,345,778
It should be:
-
100,555,333,333,666,777
-
200,444,555,453,345,778
Any ideas?
EDIT: Question has been modified to show that it was a linebreak that was being inserted into the string, not a space.
It’s not clear from your code where the space comes from, and the best way for getting rid of the space is probably to prevent it from ever occurring in the first place.
In addition, the space will not cause Excel to add a line break (I’ve just tested it to make sure). In fact, Excel silently swallows the space. If a line break is inserted in your case, that suggests that the character isn’t a whitespace but something else.
Apart from that, your code for removing whitespace works. You probably forgot to assign the result to a variable:
Edit: since it’s apparently a carriage return character rather than a space, use this:
Or, if it’s a full Windows-style line break:
If neither of these works (weird!), try this:
In other news, you should use a
StringBuilderhere instead, it will perform much better than lots of repeated string concatenations.