how to check checklistbox items using datagridview vb.net? - vb.net

I'm just a beginner for coding and I want to programmatically check items in checklistbox using datagridview.
Data grid view values are seperated with commas like this jhon,Metilda,saman,.
Checklistbox name as chklistinput and please help me to solve this ?
'Full coding is here..............................
Private Sub TextBox10_TextChanged(sender As Object, e As EventArgs) Handles TextBox10.TextChanged
'this is ok and searching as I want
Dim SearchV As String = TextBox10.Text
SearchV = "%" + TextBox10.Text + "%"
Me.PassIssuingRecordTableAdapter.FillBy(Me.Database4DataSet.PassIssuingRecord, SearchV)
'But the problem bigins here
Dim areasback As String = DataGridView1.Rows(0).Cells(6).Value.ToString
Dim areasback1 As String() = areasback.Split(",")
For Each x In areasback1
For i = 0 To areasback.Count - 1
If chklistInput.Items(i).ToString() = x.ToString() Then
chklistInput.SetItemChecked(i, False)
End If
Next
Next
End Sub

You have to loop over chklistInput.Items.Count - 1 instead of areasback.Count - 1
use the following code:
Dim areasback As String = DataGridView1.Rows(0).Cells(6).Value.ToString
Dim areasback1 As String() = areasback.Split(",")
Dim intCount as integer = 0
For each str as string in areasback1
For intCount = 0 To chklistInput.Items.Count - 1
If chklistInput.Items(intCount).ToString() = str Then
chklistInput.SetItemChecked(intCount , True)
End If
Next
Next
chklistInput.Refresh()
Note: comparing is case sensitive

Related

Find all instances of a word in a string and display them in textbox (vb.net)

I have a string filled with the contents of a textbox (pretty large).
I want to search through it and display all occurances of this word. In addition I need the searchresult to display some charachters in the string before and after the actual searchterm to get the context for the word.
The code below is part of a code that takes keywords from a listbox one by one using For Each. The code displays the first occurance of a word together with the characters in front and after the word - and stop there. It will also display "no Match for: searched word" if not found.
As stated in the subject of this question - I need it to search the whole string and display all matches for a particular word together with the surrounding characters.
Where = InStr(txtScrape.Text, Search)
If Where <> 0 Then
txtScrape.Focus()
txtScrape.SelectionStart = Where - 10
txtScrape.SelectionLength = Where + 50
Result = txtScrape.SelectedText
AllResults = AllResults + Result
Else
AllResults = AllResults + "No Match for: " & item
End If
I recommend that you can split the string into long sentences by special symbols, such as , : ? .
Split(Char[])
You can refer to the following code.
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
RichTextBox1.Text = ""
Dim Index As Integer
Dim longStr() As String
Dim str = TextBox3.Text
longStr = TextBox1.Text.Split(New Char() {CChar(":"), CChar(","), CChar("."), CChar("?"), CChar("!")})
Index = 0
For Each TheStr In longStr
If TheStr.Contains(str) Then
RichTextBox1.AppendText(longStr(Index) & vbCrLf)
End If
Index = Index + 1
Next
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
TextBox1.Text = "....."
End Sub
End Class
Result:
Try like this:
Dim ArrStr() As String
Dim Index As Integer
Dim TheStr As String
Dim MatchFound As Boolean
MatchFound = False
ArrStr = Split(txtScrape.text," ")
Index = 1
For Each TheStr In ArrStr
If TheStr = Search Then
Console.WriteLine(Index)
MatchFound = True
End If
Index = Index + 1
Next
Console.WriteLine(MatchFound)
Inside the If statement you will get the index there. And MatchFound is the Boolean value if match found.

Removing duplicates in Text Box and adding the corresponding values

I have a VB form with three TextBoxes. Here's an example of what I'd like the program to achieve:
So, that's the form ... the program sorts a text file and gets names, goals, and positions. E.g.
Jordan 26 Center
James 10 Mid
Jordan 4 Center
Jack 6 Forward
James 10 Mid
When the update button is clicked, the program should realize that James and Jordan are written twice, remove one of them and add their goals, so it should output:
Jordan 30 Center
James 20 Mid
Jack 6 Forward
To do this I've had the data transferred into ListBoxes which makes it easier to remove duplicates, the data is then transferred back into a multi-line TextBox so it is editable. Here's my code so far. It either gives the wrong results or an index out of range error.
Dim Count1 As Integer
Dim Count2 As Integer
Dim Count3 As Integer
Dim NewInt As Integer
Dim ValOne As Integer
Dim ValTwo As Integer
ListBox1.Items.Clear()
ListBox2.Items.Clear()
ListBox3.Items.Clear()
NewInt = 0
ValOne = 0
ValTwo = 0
ListBox1.Items.AddRange(Players.Text.Split(vbNewLine))
ListBox2.Items.AddRange(Goals.Text.Split(vbNewLine))
ListBox3.Items.AddRange(Positions.Text.Split(vbNewLine))
Count1 = ListBox1.Items.Count
Count2 = ListBox2.Items.Count
Count3 = ListBox3.Items.Count
If Count1 = Count2 And Count1 = Count3 And Count2 = Count3 Then
'Set two counters to compare all words with each other
For iFirstCounter As Integer = 0 To ListBox1.Items.Count - 1
For iSecondCounter As Integer = 0 To ListBox1.Items.Count - 1
'Make sure there will not be an 'out of range' error,
'because you are removing items from the listbox.
iSecondCounter = Convert.ToInt64(iSecondCounter)
iFirstCounter = Convert.ToInt64(iFirstCounter)
ListBox2.Items.RemoveAt(iSecondCounter)
ListBox2.Items.RemoveAt(iFirstCounter)
If iFirstCounter < iSecondCounter Then
ListBox2.Items.Insert(iFirstCounter, NewInt.ToString)
Else
ListBox2.Items.Insert(iSecondCounter, NewInt.ToString)
End If
Next
Next
Players.Text = ""
Goals.Text = ""
Positions.Text = ""
Dim i As Integer
For i = 0 To ListBox1.Items.Count - 1
If Players.Text = "" Then
Players.Text = ListBox1.Items(i)
Else
Players.Text = Players.Text & vbNewLine & ListBox1.Items(i)
End If
Next
Dim a As Integer
For a = 0 To ListBox2.Items.Count - 1
If Goals.Text = "" Then
Goals.Text = ListBox2.Items(a)
Else
Goals.Text = Goals.Text & vbNewLine & ListBox2.Items(a)
End If
Next
Dim b As Integer
For b = 0 To ListBox3.Items.Count - 1
If Positions.Text = "" Then
Positions.Text = ListBox3.Items(b)
Else
Positions.Text = Positions.Text & vbNewLine & ListBox3.Items(b)
End If
Next
Else
MessageBox.Show("The Text Boxes don't contain an equal number of values ... please add more/remove some values")
End If
Could be done in multiple ways, for example:
If TextBox2.Lines.Count > 1 Then
Dim LineList As List(Of String) = TextBox2.Lines.ToList 'textbox lines
Dim NewLines As List(Of String) = TextBox2.Lines.ToList 'can't edit list we're looping over, a copy of lines
Dim NamesList As New List(Of String)
For x = 0 To LineList.Count - 1
Dim linesplit As String() = LineList(x).Split({" "}, StringSplitOptions.RemoveEmptyEntries)
If NamesList.Contains(linesplit(0)) Then
NewLines.Remove(LineList(x))
Else
NamesList.Add(linesplit(0))
End If
Next
TextBox2.Lines = NewLines.ToArray
End If
Here's an example of code that does this via LINQ and Lambdas.
Module Module1
Sub Main()
Dim ungroupedPlayers(1) As String
ungroupedPlayers(0) = "Jordan 26 Center"
ungroupedPlayers(1) = "Jordan 4 Center"
Dim players = ungroupedPlayers.ToList().ConvertAll(Of Player)(Function(x As String) As Player
Dim split() As String = x.Split(" "c)
Dim p As New Player
p.PlayerName = split(0)
p.Count = split(1)
p.Position = split(2)
Return p
End Function)
Dim playersGrouped = From p In players
Group By PlayerName = p.PlayerName Into g = Group
Select PlayerName, Count = g.Sum(Function(ip As Player) ip.Count), Position = g.Min(Function(ip As Player) ip.Position.ToString())
Dim groupedPlayers() As String = playersGrouped.ToList().ConvertAll(Of String)(Function(ip)
Return ip.PlayerName.ToString() & " " & ip.Count.ToString() & " " & ip.Position.ToString()
End Function).ToArray()
For Each groupedPlayer as String in groupedPlayers
Console.WriteLine(groupedPlayer)
Next
Console.Read()
End Sub
Public Class Player
Public PlayerName As String
Public Count As Integer
Public Position As String
End Class
End Module
You don't need heavy ListBox control for working with players data.
Use List(Of T) and create class Player for better readability.
You can remove duplicates before you will display values in your form.
And instead of multiline textbox you can use DataGridView as "right tool for the editing data".
Public Class Player
Public Property Name As String
Public Property Position As String
Public Property Goals As Integer
End
Public Class PlayersForm : Form
Private Sub Form_Load(sender As Object, e As System.EventArgs) Handles MyBase.Load
Dim data As List(Of Player) = LoadPlayersData()
Dim players As List(Of Player) = NormalizeData(data)
' Use DataGridView
Me.DataGridView1.DataSource = players
End Sub
Private Function LoadPlayersData() As List(Of Player)
Dim rawData As String() = File.ReadAllLines("pathToTextFile")
Return rawData.Select(Function(line) LineToPlayer(line)).ToList()
End Function
Private Function NormalizeData(players As List(Of Player)) As List(Of Player)
Return players.Group(Function(player) player.Name)
.Select(Function(group)
Return New Player With
{
.Name = group.Key,
.Position = group.First().Position,
.Goals = group.Sum(Function(player) player.Goals)
}
End Function)
.ToList()
End Function
Private Function LineToPlayer(line As String) As Player
Dim values = line.Split(" "c)
Return New Player With
{
.Name = values(0),
.Position = values(2),
.Goals = Integer.Parse(values(1))
}
End Function
End Class
DataGridView control will automatically update your List(Of Players) when you make any change. which give you possibility to have some other controls which automatically display best scorers for example, without extra converting data from string to integer and back.

getting System.InvalidOperationException: Listbox DataSource VB.net

This is the error I am getting
System.InvalidOperationException: 'List that this enumerator is bound to has been modified. An enumerator can only be used if the list does not change.'
I have a Listbox that is databound The list of items are stored days table the saved value is stored in a record table. The List is a Comma Separated List E.G: 1,2,3,4,5
Would equate to Items with values of 1 -5 being selected on load.
This is the save Routine which Works perfectly
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.Leave
Dim listboxItems As New List(Of String)
For Each row As DataRowView In ListBox1.SelectedItems
listboxItems.Add(row("IDNum"))
Next row
selectLoad = True
lblDays.Text = String.Join(",", listboxItems.ToArray())
End Sub
This is Routine Which is Throwing the error.
Private Sub BGWLoadData_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BGWLoadData.RunWorkerCompleted
Dim TextBoxStrings() As String = {""}
Try
Dim TempStr() As String = lblDays.Text.Split(",")
ReDim TextBoxStrings(TempStr.Count - 1)
TextBoxStrings = TempStr
Catch ex As Exception
End Try
Dim TextBoxDoubles(TextBoxStrings.Count - 1) As Double
For a As Integer = 0 To TextBoxStrings.Count - 1
Try
TextBoxDoubles(a) = TextBoxStrings(a)
Catch ex As Exception
TextBoxDoubles(a) = 0
End Try
Next
Do While DaysBound = False
Application.DoEvents()
Loop
ListBox1.SelectedItems.Clear()
Dim TempIndex As Integer = 0
For Each row As DataRowView In ListBox1.Items
For a As Integer = 0 To TextBoxDoubles.Count - 1
If row("IDNum") = TextBoxDoubles(a) Then
ListBox1.SetSelected(TempIndex, True)
End If
Next
TempIndex = TempIndex + 1
Next row
End Sub
What am I doing wrong or what can be done to make the code more efficient.
Edit:
Error Occurs at Next Row.
Also telling me I have done something wrong isn't helpful I know something is Wrong because I am getting errors. I am asking for is how to fix this with a code snippet or something.
This Has been Solved by Adding a second arrary
If selectLoad = False Then
' convert CSV of IDNums of selected items in listbox into string array
Dim TextBoxStrings() As String = {""}
Try
Dim TempStr() As String = lblDays.Text.Split(",")
ReDim TextBoxStrings(TempStr.Count - 1)
TextBoxStrings = TempStr
Catch ex As Exception
End Try
' convert string array to double array
Dim TextBoxDoubles(TextBoxStrings.Count - 1) As Double
For a As Integer = 0 To TextBoxStrings.Count - 1
Try
TextBoxDoubles(a) = TextBoxStrings(a)
Catch ex As Exception
TextBoxDoubles(a) = -1
End Try
Next
' load underlying IDNums into temporary array
Dim TempIndex As Integer = 0
Dim TempIDNums(ListBox1.Items.Count - 1) As Integer
For Each row As DataRowView In ListBox1.Items
TempIDNums(TempIndex) = row("IDNum")
TempIndex = TempIndex + 1
Next row
' if any of the underlying IDNums are found in the CSV, select that item in the listbox
ListBox1.SelectedItems.Clear()
For ListItemCounter As Integer = 0 To TempIDNums.Count - 1
For SelectedItemCounter As Integer = 0 To TextBoxDoubles.Count - 1
If TempIDNums(ListItemCounter) = TextBoxDoubles(SelectedItemCounter) Then
ListBox1.SetSelected(ListItemCounter, True)
End If
Next
Next
End If

Multiline Textbox to Datagridview

I have a multi-line textbox with this appearance:
A#B
C#
D#E
and I want to populate my datagridview to something like this:
_________
|A|BC|D|E|
I mean, I want to split when there's a "#" , but I don't want multi-line cells in datagridview.
I tried this code:
Dim sup() As String = TextBox1.Text.Split(vbCr, vbLf, vbTab, " "c, "#")
DataGridView1.Rows.Add(sup(0), sup(1), sup(2),sup(3))
but it says it goes outta bounds ... Thanks!
edit:
"Index out of range exception" Error.
If i paste the textbox values to microsoft word they come like this:
If you are sure you will be splitting your textbox with 3 #'s, you could use something like this after creating 3 columns in your datagridview
Dim myStr As String
Dim substring As String
Dim strArray() As String
Dim columnInt as Integer = 0
myStr = Textbox1.Text
strArray = myStr.Split("#")
For i = 0 to strArray.Length - 1
Datagridview.Rows(0).Cells(columnInt).Value = strArray(i)
columnInt += 1
next
As I am not quite sure how you want this data to appear exactly, you may also need to declare the count of your columns should it be larger than 3. Add this code before the first For Statement:
For i = 0 to strArray.Length - 1
DataGridView.Columns.Add("YourText","YourText")
Next
Untested but it should get you in the right spot!
*Edit: Updated after testing
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer4.Tick
If DataGridView1.RowCount = 1 Then DataGridView1.Rows.Clear()
Call dgvstuff()
Timer1.Stop()
End Sub
Sub dgvstuff()
Dim sup2 = TextBox2.Text.Replace("#", "").Replace(">", " "c)
Dim sup() = sup2.Split(" "c, "#", vbCrLf, vbTab)
With DataGridView1
.Rows(0).Cells(0).Value = sup(1).ToString
.Rows(0).Cells(1).Value = sup(7).ToString
.Rows(0).Cells(3).Value = sup(4).ToString
End With
End Sub
I really don't know why but it works like this. Anyone knows a better/cleaner way? Tks

Basic Name Sorting Program using VB.net

My teacher has instructed our class to create a basic word sorting program the 'old fashioned way' in visual basic. So comparing two array values, a and b, then if one is considered higher in the order than the other, swap them if not do nothing, continue until there are no more swaps. Here is the code I have so far:
Imports System.IO
Imports System
Public Class Form1
Public arrText As New ArrayList()
Private Sub btnImprt_Click(sender As Object, e As EventArgs) Handles btnImprt.Click
'Dim OpenAnswerFile As New OpenFileDialog
Dim objReader As New StreamReader("c:\Users\Adam\Desktop\unSortList.txt")
Dim sLine As String = ""
Dim arrText As New ArrayList()
Do
sLine = objReader.ReadLine()
If Not sLine Is Nothing Then
arrText.Add(sLine)
End If
Loop Until sLine Is Nothing
objReader.Close()
Dim i As Integer = 0
txtImport.Text = arrText(i)
End Sub
Private Sub btnSort_Click(sender As Object, e As EventArgs) Handles btnSort.Click
Dim i As Integer = 0
Dim a As Integer = i + 1
txtImport.Text = i
txtImport.Text = a
Dim Temp As String
Dim Change As Boolean = True
While Change = True
Change = False
For Each i In arrText(i) - 1
If String.Compare(arrText(i), arrText(i + 1)) = 1 Then
Change = True
Temp = arrText(i)
arrText(i) = arrText(i + 1)
arrText(i + 1) = Temp
End If
Next
i = 0
End While
txtSort.Text = arrText(39)
End Sub
My problem is that I am getting an Index error and I'm not sure where the error is located as the logic seems fine.
And yes I am aware of the sorting function built into Visual Basic. but as the teacher said. No cheating.
Your code has several flaws, which I'm ignoring and just concentrating on the sorting part, as your query is related to that. Replace your sort loop with the following and check again. The basic problem was that your loop should only iterate up to List.Count - 2 and not List.Count - 1 because you're comparing List(i) and List(i + 1) inside the loop:
Dim Temp As String
Dim Change As Boolean = True
While Change
Change = False
For i = 0 To arrText.Count() - 2
If String.Compare(arrText(i), arrText(i + 1)) = 1 Then
Change = True
Temp = arrText(i)
arrText(i) = arrText(i + 1)
arrText(i + 1) = Temp
End If
Next
End While