My problem
Index was outside the bounds of the array. when i try to run the code , it generates this error
i have two forms : SIGN IN and SIGN UP , my problem is they don't work together and generates the error attached below
Dim fs As New FileStream("C:\Users\Selmen\Desktop\vb\logs.txt", FileMode.Open, FileAccess.ReadWrite)
Dim sr As New StreamReader(fs)
Dim sw As New StreamWriter(fs)
Dim s As String
Dim t() As String
Dim trouve As Integer = 0
Dim tt() As String
Dim ch As String
ch = TextBox1.Text + "#" + TextBox2.Text + "#" + TextBox3.Text + "#" + TextBox4.Text + "#" + TextBox5.Text
tt = ch.Split("#")
Do While (trouve = 0) And (sr.Peek > -1)
s = sr.ReadLine
t = s.Split("#")
If String.Compare(t(2), tt(2)) = 0 Then
trouve = 1
End If
Loop
If (trouve = 1) Then
MsgBox("user existant")
Else
sw.WriteLine(ch)
Me.Hide()
Form4.Show()
End If
sw.Close()
sr.Close()
fs.Close()
End Sub
If String.Compare(t(2), tt(2)) = 0 Then I get:
IndexOutOfRangeException was unhandled / Index was outside the bounds of the array.
Streams need to be disposed. Instead of using streams you can easily access a text file with the .net File class.
File.ReadAllLines returns an array of lines in the file. We can loop through the lines in a For Each. The lower case c following the "#" tells the compiler that you intend a Char not a String. String.Split expects a Char. Normally, String.Compare is used to order strings in alphabetical order. You just need an =. As soon as we find a match we exit the loop with Exit For.
We don't actually need the array of the text boxes Text property unless there is no match. Putting the elements in braces intializes and fills the array of String.
File.AppendAllLines does what it says. It is expecting an array of strings. As with the text boxes, we put our line to append in braces.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim p = "path to file"
Dim lines = File.ReadAllLines(p)
Dim trouve As Integer
For Each line In lines
Dim thirdField = line.Split("#"c)(2)
If thirdField = TextBox3.Text Then
trouve = 1
Exit For
End If
Next
If trouve = 1 Then
MsgBox("user existant")
Else
Dim tt = {TextBox1.Text, TextBox2.Text, TextBox3.Text, TextBox4.Text, TextBox5.Text}
File.AppendAllLines(p, {String.Join("#", tt)})
Me.Hid3e()
Form4.Show()
End If
End Sub
I have created a service that is supposed to pass data from SQL to CSV, by creating a CSV file. It has no errors, but i run it and nothing happens.
1) Is there something I am missing?
2) If it works, and i want to convert to txt file, is it enough to change the "CSV" to "txt" parts?
My code:
#Region "Export SQL TO CSV"
Public Shared Function WriteCSV(ByVal input As String) As String
Try
If (input Is Nothing) Then
Return String.Empty
End If
Dim containsQuote As Boolean = False
Dim containsComma As Boolean = False
Dim len As Integer = input.Length
Dim i As Integer = 0
Do While ((i < len) _
AndAlso ((containsComma = False) _
OrElse (containsQuote = False)))
Dim ch As Char = input(i)
If (ch = Microsoft.VisualBasic.ChrW(34)) Then
containsQuote = True
ElseIf (ch = Microsoft.VisualBasic.ChrW(44)) Then
containsComma = True
End If
i = (i + 1)
Loop
If (containsQuote AndAlso containsComma) Then
input = input.Replace("""", """""")
End If
If (containsComma) Then
Return """" & input & """"
Else
Return input
End If
Catch ex As Exception
Throw
End Try
End Function
Private Sub ExtoCsv(ByVal sender As Object, ByVal e As EventArgs)
Dim sb As StringBuilder = New StringBuilder
Using db As Database.RecordSet = admin.Database.OpenRecordsetReadOnly("select USERID, NAME1 from usertable WHERE I_ID=2")
Dim userid As String = db("USERID").Value
Dim name1 As String = db("NAME1").Value
For i As Integer = 1 To db.RecordCount
sb.Append(WriteCSV(userid + "," + name1 + ","))
sb.AppendLine()
db.MoveNext()
Next
End Using
File.WriteAllText("C:\Users\user1\Desktop\ex1.csv", sb.ToString)
If (Not System.IO.Directory.Exists("C:\Users\user1\Desktop\ex1")) Then
System.IO.Directory.CreateDirectory("C:\Users\user1\Desktop\ex1")
End If
End Sub
#End Region
I want to compare the Textbox1 with TextBox2, or Textbox line 1 of the text box to the 2nd line, to show me the existing Character in another textbox, or show me how many characters are repeated. iI really like learning, so I would be helpful because I want to learn...
TextBox1.Text = 1,4,7,11,13,16,19,20,28,31,44,37,51,61,62,63,64,69,71,79,80
TextBox2.Text = 1,5,7,10,13,16,26,20,28,31,44,37,51,72,73,74,69,71,79,80
TextBox3.Text = Character Repeated: 1,7,13,16,20,28,31,44,37,51,69,71,79,80
TextBox4.Text = Number of Character Repeated = 14
TextBox5.Text = Number of Character which has not been repeated: 4,11,19,61,62,63,64 etc, you got to idea
TextBox6.Text = Number of Character isn't Repeated: 7
here are some codes: but I do not know how to apply them correctly.
Code 1: Show repetable character:
' Split string based on space
TextBox1.Text = System.IO.File.ReadAllText(Mydpi.Text)
TextBox2.Text = System.IO.File.ReadAllText(Mydpi.Text)
TextBox4.Text = System.IO.File.ReadAllText(Mydpi.Text)
For i As Integer = 0 To TextBox2.Lines.Count - 1
Dim textsrtring As String = TextBox4.Lines(i)
Dim words As String() = textsrtring.Split(New Char() {","c})
Dim found As Boolean = False
' Use For Each loop over words
Dim word As Integer
For Each word In words
TxtbValBeforeCompar.Text = TextBox1.Lines(i)
CompareNumbers()
If TextBox1.Lines(i).Contains(word) Then
found = True
Dim tempTextBox As TextBox = CType(Me.Controls("Checkertxt" & i.ToString), TextBox)
On Error Resume Next
If TextBox2.Lines(i).Contains(word) Then
If tempTextBox.Text.Contains(word) Then
Else
tempTextBox.Text = tempTextBox.Text + " " + TxtbValAfterCompar.Text()
End If
Else
End If
End If
Next
Next
Private Sub CompareNumbers()
'First Textbox that is to be used for compare
Dim textBox1Numbers As List(Of Integer) = GetNumbersFromTextLine(N1Check.Text)
'Second Textbox that is to be used for compare
Dim textBox2Numbers As List(Of Integer) = GetNumbersFromTextLine(TxtbValBeforeCompar.Text)
'Union List of Common Numbers (this uses a lambda expression, it can be done using two For Each loops instead.)
Dim commonNumbers As List(Of Integer) = textBox1Numbers.Where(Function(num) textBox2Numbers.Contains(num)).ToList()
'This is purely for testing to see if it worked you can.
Dim sb As StringBuilder = New StringBuilder()
For Each foundNum As Integer In commonNumbers
sb.Append(foundNum.ToString()).Append(" ")
TxtbValAfterCompar.Text = (sb.ToString())
Next
End Sub
Private Function GetNumbersFromTextLine(ByVal sTextLine As String) As List(Of Integer)
Dim numberList As List(Of Integer) = New List(Of Integer)()
Dim sSplitNumbers As String() = sTextLine.Split(" ")
For Each sNumber As String In sSplitNumbers
If IsNumeric(sNumber) Then
Dim iNum As Integer = CInt(sNumber)
TxtbValAfterCompar.Text = iNum
If Not numberList.Contains(iNum) Then
TxtbValAfterCompar.Text = ("")
numberList.Add(iNum)
End If
Else
End If
Next
Return numberList
End Function
Code 2: Remove Duplicate Chars (Character)
Module Module1
Function RemoveDuplicateChars(ByVal value As String) As String
' This table stores characters we have encountered.
Dim table(value.Length) As Char
Dim tableLength As Integer = 0
' This is our result.
Dim result(value.Length) As Char
Dim resultLength As Integer = 0
For i As Integer = 0 To value.Length - 1
Dim current As Char = value(i)
Dim exists As Boolean = False
' Loop over all characters in the table of encountered chars.
For y As Integer = 0 To tableLength - 1
' See if we have already encountered this character.
If current = table(y) Then
' End the loop.
exists = True
y = tableLength
End If
Next
' If we have not encountered the character, add it.
If exists = False Then
' Add character to the table of encountered characters.
table(tableLength) = current
tableLength += 1
' Add character to our result string.
result(resultLength) = current
resultLength += 1
End If
Next
' Return the unique character string.
Return New String(result, 0, resultLength)
End Function
Sub Main()
' Test the method we wrote.
Dim test As String = "having a good day"
Dim result As String = RemoveDuplicateChars(test)
Console.WriteLine(result)
test = "areopagitica"
result = RemoveDuplicateChars(test)
Console.WriteLine(result)
End Sub
End Module
You could make use of some LINQ such as Intersect and Union.
Assuming your TextBox1 and TextBox2 contains the text you have provided.
Here's a simple method to find repeated and non repeated characters.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim firstBoxList = TextBox1.Text.Split(",").ToList()
Dim secondBoxList = TextBox2.Text.Split(",").ToList()
Dim intersectionList = firstBoxList.Intersect(secondBoxList)
For Each str As String In intersectionList
TextBox3.Text = TextBox3.Text & str & ","
Next
TextBox4.Text = intersectionList.Count()
Dim notRepeatedCharacter = firstBoxList.Union(secondBoxList).ToList
notRepeatedCharacter.RemoveAll(Function(x) intersectionList.Contains(x))
For each str As String In notRepeatedCharacter
TextBox5.Text = TextBox5.Text & str & ","
Next
TextBox6.Text = notRepeatedCharacter.Count()
End Sub
The output is something like that:
This consider both of the textboxes not repeated character.
If you just want to find the not repeated characters from first list to the second, this should do it:
firstBoxList.RemoveAll(Function(x) secondBoxList.Contains(x))
For Each str As String In firstBoxList
TextBox7.Text = TextBox7.Text & str & ","
Next
TextBox8.Text = firstBoxList.Count
And this is the output:
Here's the full code using String.Join to make the lists look smoother in the text boxes:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'First we grab all the numbers written inside the textboxes (I am not verifying anything)
Dim firstBoxList = TextBox1.Text.Split(",").ToList()
Dim secondBoxList = TextBox2.Text.Split(",").ToList()
'Second we intersect the two lists and show them
Dim intersectionList = firstBoxList.Intersect(secondBoxList)
TextBox3.Text = String.Join(",", intersectionList)
TextBox4.Text = intersectionList.Count()
'We're checking the distintc character from both lists
Dim notRepeatedCharacter = firstBoxList.Union(secondBoxList).ToList
notRepeatedCharacter.RemoveAll(Function(x) intersectionList.Contains(x))
TextBox5.Text = String.Join(",", notRepeatedCharacter)
TextBox6.Text = notRepeatedCharacter.Count()
'we're checkng the distinct character inside first list that doesn't show in second list
firstBoxList.RemoveAll(Function(x) secondBoxList.Contains(x))
TextBox7.Text = String.Join(",", firstBoxList)
TextBox8.Text = firstBoxList.Count
End Sub
I have been trying to create a program that will find the word the user has clicked on, in a multiline textbox. This procedure is based on the index from the position of the click. The code I implemented:
Public Class Form1
Private Sub TextBox1_MouseDown(sender As Object, e As MouseEventArgs) Handles TextBox1.MouseDown
If e.Clicks = 1 And e.Button = MouseButtons.Left Then
'Try
Dim indexClicked As Integer = TextBox1.GetCharIndexFromPosition(New Point(e.X, e.Y))
Dim ch As Char = TextBox1.Text.Chars(indexClicked)
Dim indexOfWord As Int32
If Not ch = " " Then
Dim wordFound As Boolean
Dim previousCh As Char
Dim previousIndex As Integer = indexClicked
While Not wordFound
previousIndex = previousIndex - 1
previousCh = TextBox1.Text.Chars(previousIndex)
If previousCh = " " Then
indexOfWord = previousIndex + 1
wordFound = True
End If
End While
Else
indexOfWord = indexClicked + 1
End If
Label1.Text = indexClicked & ", " & indexOfWord
Label2.Text = GetWordByIndex(TextBox1.Text, indexOfWord)
' Catch ex As Exception
' Label2.Text = ex.Message
' End Try
End If
End Sub
Public Shared Function GetWordByIndex(input As String, index As Integer) As String
Try
Dim words = input.Split(" ")
If (index < 0) OrElse (index > words.Length - 1) Then
Throw New IndexOutOfRangeException("Index out of range!")
End If
Return words(index)
Catch ex As Exception
'handle the exception your way
Return String.Empty
End Try
End Function
End Class
The problem is that whenever the program reaches the line:
previousCh = TextBox1.Text.Chars(previousIndex)
it exits with :
An unhandled exception of type 'System.IndexOutOfRangeException' occurred in WindowsApplication1.exe
Additional information: Index was outside the bounds of the array.
While the exception is thrown, by hovering over the previousIndex variable visual studio shows me its value: -1.
I think that previousCh = " " condition never gets true, so the program never exits the while loop, which keeps looking for the previous character. At some point int previousIndex gets negative and the program crashes. Why does not the condtion work properly?
What is the problem?
Thank you.
If you do not want to have the user double click like David Wilson suggested (which i would also agree with) then this will get the result you want. It takes into account if the previous character is a line feed or the start of the text, or the next character is a line feed or end of the text as well. You can add to the If to find "," or "." if needed.
Private Sub TextBox1_MouseDown(sender As Object, e As MouseEventArgs) Handles TextBox1.MouseDown
If e.Clicks = 1 And e.Button = MouseButtons.Left Then
Dim startIndex As Integer = TextBox1.SelectionStart
Dim wordStartFound, wordEndFound As Boolean
Dim nextIndex, indexOfStartOfWord, indexOfEndOfWord, lengthOfWord As Integer
If Not startIndex = 0 Then
While Not wordStartFound
startIndex = startIndex - 1
If TextBox1.Text.Chars(startIndex) = " " Then
indexOfStartOfWord = startIndex + 1
wordStartFound = True
ElseIf startIndex = 0 Then
indexOfStartOfWord = startIndex
wordStartFound = True
ElseIf TextBox1.Text.Chars(startIndex) = Chr(10) Then 'Line Feed'
indexOfStartOfWord = startIndex + 1
wordStartFound = True
End If
End While
Else
indexOfStartOfWord = startIndex
End If
nextIndex = startIndex
While Not wordEndFound
nextIndex = nextIndex + 1
If TextBox1.Text.Chars(nextIndex) = " " Then
indexOfEndOfWord = nextIndex
wordEndFound = True
ElseIf nextIndex = TextBox1.TextLength - 1 Then
indexOfEndOfWord = TextBox1.TextLength
wordEndFound = True
ElseIf TextBox1.Text.Chars(nextIndex) = Chr(10) Then 'Line Feed'
indexOfEndOfWord = nextIndex
wordEndFound = True
End If
End While
lengthOfWord = indexOfEndOfWord - indexOfStartOfWord
Label2.Text = TextBox1.Text.Substring(indexOfStartOfWord, lengthOfWord)
End If
End Sub
Also in your function GetWordByIndex you split the input string into an array
Dim words = input.Split(" ")
then you say
If (index < 0) OrElse (index > words.Length - 1) Then
Throw New IndexOutOfRangeException("Index out of range!")
End If
but when you call .length on an array it returns the number of strings (or whatever is in the array) For example if the input was "The big brown fox jumped over the lazy dog", words.length - 1 will return 8. So if your index you pass through is the start of the word "over" it would fall into the Throw New IndexOutOfRangeException("Index out of range!") as the index would be 26 which is obviously greater than 8.
The code i have provided doesn't use the function to find the word but i thought i would mention that anyway.
I have a combobox populated by a datatable, the code searches for a text string located at any position of the field while the user is writing, so far no problem.
So the problem is: When I write the third character the combobox autocompletes with the first result, and there is no way to type anything else.
I have tried already using all AutocompleteMode & AutocompleteSourse properties settings and combinations.
That’s why I’m asking for help.
The code is below:
Private Sub ComboListadoRemitente_KeyUp(sender As Object, e As KeyEventArgs) Handles ComboListadoRemitente.KeyUp
Dim strText As String
strText = ComboListadoRemitente.Text
If Len(strText) > 2 Then
ComboListadoRemitente.DataSource = dtListado.Select("listado LIKE '%" & strText & "%'")
ComboListadoRemitente.DroppedDown = True
Cursor.Current = Cursors.Default
End If
End Sub
Thanks
Finally I got something that works well, it is not the final version, surely can be further improved, here is the code:
Public Sub ComboListadoRemitente_KeyUp(sender As Object, e As KeyEventArgs) Handles ComboListadoRemitente.KeyUp
Dim strText As String
strText = ComboListadoRemitente.Text
If ComboListadoRemitente.Text = "" Then
ComboListadoRemitente.DataSource = Me.dtListado
ComboListadoRemitente.ValueMember = "Id"
ComboListadoRemitente.DisplayMember = "listado"
ComboListadoRemitente.SelectedIndex = -1
ComboListadoRemitente.DroppedDown = False
End If
If Len(strText) > 2 Then
ComboListadoRemitente.DataSource = dtListado.Select("listado LIKE '%" & strText & "%'")
ComboListadoRemitente.ValueMember = "Id"
ComboListadoRemitente.DisplayMember = "listado"
If ComboListadoRemitente.Items.Count <> 0 Then
ComboListadoRemitente.DroppedDown = True
ComboListadoRemitente.SelectedIndex = -1
ComboListadoRemitente.Text = ""
ComboListadoRemitente.SelectedText = strText
strText = ""
Cursor.Current = Cursors.Default
Else
ComboListadoRemitente.DataSource = Me.dtListado
ComboListadoRemitente.ValueMember = "Id"
ComboListadoRemitente.DisplayMember = "listado"
ComboListadoRemitente.SelectedIndex = -1
ComboListadoRemitente.Text = ""
ComboListadoRemitente.SelectedText = strText
strText = ""
ComboListadoRemitente.DroppedDown = False
End If
End If
End Sub