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:
strrowvalue = strrowvalue.Replace(" ", "")
Edit: since it’s apparently a carriage return character rather than a space, use this:
strrowvalue = strrowvalue.Replace(vbCr, "")
Or, if it’s a full Windows-style line break:
strrowvalue = strrowvalue.Replace(vbCrLf, "")
If neither of these works (weird!), try this:
strrowvalue = strrowvalue.Replace(vbLf, "")
In other news, you should use a StringBuilder here instead, it will perform much better than lots of repeated string concatenations.
Depending on what kind of line break is being inserted, I'd update this line to one of the following:
strrowvalue += CStr(DataGridView1.Rows(m).Cells(0).Value).Replace(vbCrLf,"")
-- or --
strrowvalue += CStr(DataGridView1.Rows(m).Cells(0).Value).Replace(vbCr,"")
-- or --
strrowvalue += CStr(DataGridView1.Rows(m).Cells(0).Value).Replace(vbLf,"")
Related
I want to copy the last line of a rich textbox.
I am avoiding Dim lastLine As String = RichTextBox1.Lines(RichTextBox1.Lines.Length - 1)as
it's not working properly, as It works just if there are atleast 2 lines in it.
I'm trying with MsgBox(RichTextBox1.Lines(UBound(richtextbox1.Lines))) but the problem is that even if the richtextbox has just 1 line of text but the cursor is in the second empty line, it will give back "" as I think the software is reading the empty 2nd line.
There is a solution to that?
Thanks
This will get the last non-empty line:
RichTextBox1.Lines.Where(Function(line) line <> String.Empty).Last()
There are some potential issues with that. If there's no text at all or if there are multiple lines but they are all empty, that will throw an exception. To allow for that, you can call LastOrDefault instead, in which case it would return Nothing.
If you only want to exclude the last empty line, e.g. if you have some text followed by a line break and then another line break then you want to get the first of those two empty lines, then you can't really do it in one line:
Dim lines = RichTextBox1.Lines
Dim upperBound = lines.GetUpperBound(0)
Dim lastLine = lines(upperBound)
If lastLine = String.Empty Then
If upperBound > 0 Then
lastLine = lines(upperBound - 1)
Else
lastLine = Nothing
End If
End If
'Use lastLine here.
So basically what I am trying to do in vb.net is remove multiple nested parentheses and all the text inside those parentheses from a string. It's easy to do if there is just one set of parentheses like in the first example below I just find the index of "(" and ")" and then use the str.remove(firstindex, lastindex) and just keep looping until all parentheses have been removed from the string.
str = "This (3) is(fasdf) an (asdas) Example"
Desired output:
str = "This is an example"
However I still can't figure out how to do it if their are multiple nested parentheses in the string.
str = "This ((dsd)sdasd) is ((sd)) an (((d))) an example"
Desired Outcome:
str = "This is an example"
This isn't really a tutorial site, so I shouldn't be answering this, but I couldn't resist.
As Ahmed said, you could use Regex.Replace, but I find Regexes complex and impenetrable. So it would be difficult for someone else to maintain it.
The following code has three loops. The our loop, a While loop, will run the two inner loops as long as the character index is less than the length of the string.
The first inner loop searches for the first "open bracket" in a group and records the position and adds 1 to the number of "open brackets" (the depth). Any subsequent "open brackets" just adds 1 to the number of brackets. This carries on until the first loop finds a "close bracket"
Then the second loop searches for the same number of "close brackets" from that point where the first "close bracket" is found.
When the loop gets to the last "close bracket" in the group, all the characters from the first "open bracket" to the last "close bracket" in the group are removed. Then the While loop starts again if the current index position is not at the end of the updated inputString.
When the While loop finishes, any double spaces are removed and the updated output string is returned from the function
Private Function RemoveBracketsAntContents(inputString As String) As String
Dim i As Integer
While i < inputString.Length
Dim bracketDepth As Integer = 0
Dim firstBracketIndex As Integer = 0
Do
If inputString(i) = "(" Then
If firstBracketIndex = 0 Then
firstBracketIndex = i
End If
bracketDepth += 1
End If
i += 1
Loop Until i = inputString.Length OrElse inputString(i) = ")"
If i = inputString.Length Then Exit While
Do
If inputString(i) = ")" Then
bracketDepth -= 1
End If
i += 1
Loop Until bracketDepth = 0
inputString = inputString.Remove(firstBracketIndex, i - firstBracketIndex)
i = i - (i - firstBracketIndex)
End While
inputString = inputString.Replace(" ", " ")
Return inputString
End Function
I am trying to display all the strings to be in a single line, but it is showing two words in each line. Here is my code:
For i = 0 To readCount - 1
ListBox1.Text = ListBox1.Items.Add(readBuffer(i).ToString("X2")) & vbCrLf
Next
Try using a StringBuilder to join the hexadecimal values first. Then add them to the ListBox.
Dim sb As New System.Text.StringBuilder()
For i = 0 To readCount - 1
sb.Append(readBuffer(i).ToString("X2"))
Next
ListBox1.Items.Add(sb.ToString)
If you don't want a line break, than don't use the & vbCrlf part, since that part is responsible for adding the line break between (after, actually) every item.
For i = 0 To readCount - 1
ListBox1.Text = ListBox1.Items.Add(readBuffer(i).ToString("X2"))
Next
vbCrLf is a constant that represents Carriage Return and Line Feed. Those are special chars evaluating to a newline.
Just take away the concatenation with vbCrLf. Your string should be single-line then. (Except for, when one of the input strings contains vbCrLf itself.
The following function was given to me via an answer that I asked earlier today.
What I'm trying to do is to remove a character from a string in Excel using VBA. However, whenever the function runs, it ends up erasing the value stored and returning a #!VALUE error. I cannot seem to figure out what is going on. Anyone mind explaining an alternative:
Function ReplaceAccentedCharacters(S As String) As String
Dim I As Long
With WorksheetFunction
For I = 1 To Len(S)
Select Case Asc(Mid(S, I, 1))
' Extraneous coding removed. Leaving the examples which
' do work and the one that is causing the problem.
Case 32
S = .Replace(S, I, 1, "-")
Case 94
S = .Replace(S, I, 1, "/")
' This is the coding that is generating the error.
Case 34
S = .Replace(S, I, 1, "")
End Select
Next I
End With
ReplaceAccentedCharacters = S
End Function
When the string contains a " (or character code 34 in Decimal, 22 in Hexadecimal... I used both) it is supposed to remove the quotation mark. However, instead, Excel ignores it, and still returns the " mark anyway.
I then tried to go ahead and replace the .Replace() clause with another value.
Case 34
S = .Replace(S, I, 1, "/")
End Select
Using the code above, the script indeed does replace the " with a /.
I ended up finding the following example here in Stack Overflow:
https://stackoverflow.com/a/7386565/692250
And in the answer given, I see the same exact code example similar to the one that I gave and nothing. Excel is still ignoring the quotation mark. I even went so far as to expand the definition with curly braces and still did not get anything.
Try this:
Function blah(S As String) As String
Dim arr, i
'array of [replace, with], [replace, with], etc
arr = Array(Chr(32), "-", Chr(94), "/", Chr(34), "")
For i = LBound(arr) To UBound(arr) Step 2
S = Replace(S, arr(i), arr(i + 1))
Next i
blah = S
End Function
This function was designed to replace one character with another. It was not designed to replace a character with nothing. What happens when you try to replace a character with nothing is that the Counter for iterating through the word will now look (at the last iteration) for a character position that is greater than the length of the word. That returns nothing, and when you try to determine ASC(<nothing>) an error occurs. Other errors in the replacement routine will also occur when the length of the string is changed while the code is running
To modify the routine to replace a character with nothing, I would suggest the following:
In the Case statements:
Case 34
S = .Replace(S, I, 1, Chr(1))
And in the assignment statement:
ReplaceAccentedCharacters = Replace(S, Chr(1), "")
Note that VBA Replace is different from Worksheetfunction Replace
How do I use the Indexof Method to search for an Index a number? The number will be different on each line of the file. Each array has a name and a different zip code. I want to tell it to search for the first number in the line. Everything before that index will be first name, last name, and then zip code.
infile = IO.File.OpenText("Names.txt")
'process the loop instruct until end of file
intSubscript = 0
Do Until infile.Peek = -1
'read a line
strLine(intSubscript) = infile.ReadLine
intSubscript = intSubscript + 1
Loop
infile.Close()
A solution from how I understand this:
Instead of using the IndexOf, you can save each part of the file on a different line (ReadLine).
If you really need the IndexOf: It's just String.IndexOf(EnterCharacterHere)
You could also read this file and only use the numbers found:
First you make a const string const cstrNumbers as string = "0123456789" and then do the following:
For x as integer = 0 to strInput -1
strTemporary = strInput.Substring(x,1)
If InStr(cstrNumbers, strTemporary) <> 0 Then
strOutput &= strTemporary
strOutput will contain the numbers then.
Hope this helps,
Simon
EDIT:
This would be easier with a database, but I have no experience with db in vb.net.
You could do a substring combined with the InStr I mentioned.
First you need a function that will return the first occurrence of a number. (With InStr)
And then use this in the substring (String.SubString(FirstOccurence, LengthOfZip)
Don't have the time to do the complete code now..Hope this helps you a bit