System.NullReferenceException on a ForEach of a datagrid - vb.net

So all is in the question, I have a datagrid view who's parcoured by a foreach in his rows collection like so dataGridView1.Rows and I get and error of null type in the second if of the for each
Sub DataColumnFirstDouble(ByRef dGridView As DataGridView, ByVal iCol As Integer)
Dim bFirstRow As Boolean = False
Dim sTemp As String = ""
For Each RW As DataGridViewRow In dGridView.Rows
If (bFirstRow) Then
If (RW.Cells(iCol).Value.ToString() = sTemp) Then
RW.Cells(iCol).Selected = True
dGridView.CurrentCell.Style.BackColor = Color.LightGreen
dGridView.CurrentCell.Style.ForeColor = Color.White
End If
End If
sTemp = RW.Cells(iCol).Value.ToString()
bFirstRow = True
Next
End Sub
By the way the Datagrid is populated with 1 entry going
LongString, Number, Number
Hello , 8 , 8
The bug occur when I click on a new row also the function is called on the event of row leave
Need some help
By the way what I try to do is to check when the user enter the name in the longstring space who's a primary unique key in a database but It seems I can't find anythings to handle it by vb so I try to parse it every times he leave the rows to check if there's any double

It isn't clear where the error is, you should debug to figure out which variable exactly is null. So I'll assume it's RW.Cells(iCol).Value.
If there's no value in the cell, it might be null. This mean ToString won't work.
If (bFirstRow) Then
If RW.Cells(iCol).Value IsNot Nothing AndAlso RW.Cells(iCol).Value.ToString() = sTemp Then
RW.Cells(iCol).Selected = True
dGridView.CurrentCell.Style.BackColor = Color.LightGreen
dGridView.CurrentCell.Style.ForeColor = Color.White
End If
End If
You could even check if RW.Cells(iCol) exists, maybe it's trying to fetch the data in a cell that doesn't exists in the row.

Related

How to find a toolstripitem based on its name being a variable and then change the checked value of it

I have a ContextMenuStrip called: DGVContextStrip its displayed when the user right clicks on my datagridview.
That MenuStrip contains an item called AddUpgradeTagToolStripMenuItem
which contains sub items(dropdownitems), these sub items are all named with a number in their name.
eg: Add1ToolStripMenuItem, Add2ToolStripMenuItem, Add3ToolStripMenuItem.... and so on until Add25ToolStripMenuItem.
When a user right clicks, on the Datagridview, I want to check if a cell contains the number "1" then if it does make Add1ToolStripItem.checked = true
I figured I would loop through the numbers 1 to 25, and in each loop check if the cell contains 1 and if true, change the checked value of the menu item. something like...
For i = 1 to 25
If DataGridView1.SelectedRows(0).Cells("Text_Field").Value.ToString.Contains(i) then
CType("Add" & i & "ToolStripMenuItem", ToolStripMenuItem).Checked = True
Next
but this doesn't work, iv seen examples online that use the control.find method but i couldn't get that to work for my use.
for example
Dim ControlName As String = "Add" & i & "ToolStripMenuItem"
CType(Me.Controls.Find(ControlName, True), ToolStripMenuItem).Checked = True
any ideas how I get this to work? I realise I could have used 25 if then else statements but I kind of wanted to keep the code far neater.
The ToolStripItem is not a control to search for one in a Control.ControlCollection. You need to search a ToolStripItemCollection where it belongs.
Just like the Control.ControlCollection.Find method, the ToolStripItemCollection.Find method can perform a deep search for an item.
Examples for your case:
Dim itemName As String = $"Add{i}ToolStripMenuItem"
Dim tsmi = yourContextMenuStrip.Items.
Find(itemName, True).
OfType(Of ToolStripMenuItem).
FirstOrDefault()
If tsmi IsNot Nothing Then
tsmi.Checked = True
End If
Alternatively, if you already know that the target item is one of the AddUpgradeTagToolStripMenuItem drop down items, then you can do:
Dim itemName As String = $"Add{i}ToolStripMenuItem"
Dim tsmi = DirectCast(AddUpgradeTagToolStripMenuItem, ToolStripMenuItem).
DropDownItems.OfType(Of ToolStripMenuItem).
FirstOrDefault(Function(x) x.Name.Equals(itemName, StringComparison.OrdinalIgnoreCase))
If tsmi IsNot Nothing Then
tsmi.Checked = True
End If
In case you need to check only one item from the collection:
Dim itemName As String = $"Add{i}ToolStripMenuItem"
For Each tsmi In DirectCast(AddUpgradeTagToolStripMenuItem, ToolStripMenuItem).
DropDownItems.OfType(Of ToolStripMenuItem)
If tsmi.Name.Equals(itemName, StringComparison.OrdinalIgnoreCase) Then
tsmi.Checked = True
Else
tsmi.Checked = False
End If
Next

DataGridView live search data

I am trying to add a search function to a DataGridView in vb.net using this code
For i As Integer = 0 To ContactsList.RowCount - 1
For j As Integer = 0 To ContactsList.ColumnCount - 1
If ContactsList.Rows(i).Cells(j).Value.ToString.ToLower.Trim = ContactsListSearch.Text.ToLower.Trim Then
MsgBox("Item found " + i.ToString)
ContactsList.Rows(i).Visible = True
Else
ContactsList.Rows(i).Visible = False
End If
Next
Next
I'm seeing the MsgBox show when the value matches, but the rows are not showing, it just hides all rows
Another possible option is to load data into a DataTable, create a BindingSource, set the BindingSource DataSource property to the DataTable. Set the DataGridView DataSource property to the BindingSource.
The following example works against a column in the DataTable. If the user clears the TextBox the filter is removed while if there is text filter with trim.
Private Sub SearchButton_Click(sender As Object, e As EventArgs) _
Handles SearchButton.Click
If String.IsNullOrWhiteSpace(SearchTextBox.Text) Then
bindingSource.Filter = ""
Else
Dim currentRowCount = bindingSource.Count
bindingSource.Filter = $"TRIM(LastName) = '{SearchTextBox.Text}'"
MessageBox.Show($"Before: {currentRowCount} Now: {bindingSource.Count}")
End If
End Sub
Edit If the column name might be variable consider loading a ComboBox with column names then adjust code as follows.
bindingSource.Filter = $"TRIM({FilterComboBox.Text}) = '{SearchTextBox.Text}'"
In most cases working against a data source is better than working against cells values as per the above recommendation.
I added 2 Exits in the IF statement when the value matches as it's searching each column as well, so it was causing them to be hidden as it loops columns too
For i As Integer = 0 To ContactsList.RowCount - 1
For j As Integer = 0 To ContactsList.ColumnCount - 1
If ContactsList.Rows(i).Cells(j).Value.ToString.ToLower.Trim = ContactsListSearch.Text.ToLower.Trim Then
MsgBox("Item found " + i.ToString)
ContactsList.Rows(i).Visible = True
Else
ContactsList.Rows(i).Visible = False
End If
Next
Next

How to use function to prevent duplicated record for datagridview

I use function to prevent the same record goes into my datagridview but it doesnt work , when i separate the code out then its worked
i tried to seperate the for loop part out then the code work , but i wan to use function to do it so the code look more neater
Private Sub PicFavNote10_Click(sender As Object, e As EventArgs) Handles picFavNote10.Click
If validationDataGrid(lblNameNote10.Text) <> True Then
'if item didn added to the favorite data table yet
'add to favorite table
addTofavorite(lblUserLogin.Text, lblNameNote10.Text, lblDecpNote10.Text, txtPicNote10.Text, "SmartPhone", lblPriceNote10.Text)
End If
lblPriceNote10.Text = FormatCurrency(lblPriceNote10.Text)
End Sub
Private Function validationDataGrid(ByRef data As String) As Boolean
'validation on data grid view
For Each itm As DataGridViewRow In DGTFavTable.Rows 'loop though every item in datagrid
If itm.Cells(0).Value = data Then 'check wherter the text already exist
MsgBox(data & " Already added to your favorite cart")
Return True
Else
Return False
End If
Next
End Function
I expected the MsgBox(data & " Already added to your favorite cart") will excecute but instead the validationDataGrid function return false value even the item is already added to favorite datagridview
Before you loop all rows you need to call this sub as is an efficient workaround to validate new data on DataGridView:
Private Sub ForceGridValidation()
'Get the current cell
Dim currentCell As DataGridViewCell = DGTFavTable.CurrentCell
If currentCell IsNot Nothing Then
Dim colIndex As Integer = currentCell.ColumnIndex
If colIndex < DGTFavTable.Columns.Count - 1 Then
DGTFavTable.CurrentCell = DGTFavTable.Item(colIndex + 1, currentCell.RowIndex)
ElseIf colIndex > 1 Then
DGTFavTable.CurrentCell = DGTFavTable.Item(colIndex - 1, currentCell.RowIndex)
End If
'Set the original cell
DGTFavTable.CurrentCell = currentCell
End If
End Sub

Search using textbox VB

I need to search DataGridView by date. If I enter 2/11/2017 in text box, I want grid to show me rows that contain this date. Date column in my DataGridView is named AppointmentDate and is created in SQL Server. Type of this column is only date.
I saw this, but I am using Entity Framework model, I don't know how to realize it.
dgvPacientet.CurrentCell = Nothing
Dim found As Boolean = False
For Each row As DataGridViewRow In dgvPacientet.Rows
row.Visible = row.Cells("Dt_terminit").Value = txtData.Text
If row.Visible Then found = True
Next
If Not found Then MsgBox("Item not found")`
Simply show or hide the rows that contain the text you want.
DataGridView1.CurrentCell = Nothing
Dim found as Boolean = false
For Each row As DataGridViewRow In DataGridView1.Rows
Row.Visible = Not IsDBNull(row.Cells("DT_Terminit").Value) andalso row.Cells("DT_Terminit").Value = TextBox5.Text
If Row.Visible then found = true
Next
If Not found Then MsgBox("Item not found")
However you really need to parse that textbox to make sure it is a date first and if that cell contains a true Date, you need to convert the test into a date.
Dim DT As Date
If Not Date.TryParse(TextBox5.Text, DT) Then
MsgBox("Please enter a date") '<-- remove this line if searching on the fly... (as you enter text)
Exit Sub
End If
DataGridView1.CurrentCell = Nothing
Dim found As Boolean = False
For Each row As DataGridViewRow In DataGridView1.Rows
Row.Visible = Not IsDBNull(row.Cells("DT_Terminit").Value) andalso row.Cells("DT_Terminit").Value =DT
If row.Visible Then found = True
Next
If Not found Then MsgBox("Item not found")

Cannot remove rows in datagridview in vb.net

My datagridview is bound to a data table. I want to filter the datagridview without affecting data table. I know one way is to use bindingsource, but binding source will use column names in its filter. But I want to enable users to enter any string in a textbox to filter. So I pass datagridview by reference to a function PassFilter which removes unwanted rows in datagridview. I can see that it does execute rows removal in datagridview. But the problem is that when datagridview is shown on the form, it is unchanged, the same as the data table. I do not understand why rows are not removed on datagridview
The code is as follows:
DataGridView1.DataSource = table
PassFilter(DataGridView1, m_FilterQuick.strFilter.ToLower())
Private Sub PassFilter(ByRef datagridview As DataGridView, ByVal strFilter As String)
Dim i As Integer = 0
Dim j As Integer = 0
Dim containStr As Boolean = False
While i < datagridview.Rows.Count
j = 0
containStr = False
'If all cells in a row does not contain strFilter, delete this row from datagridview
While j < datagridview.Rows(i).Cells.Count
Dim c As DataGridViewCell = datagridview.Rows(i).Cells(j)
If Not c.Value Is DBNull.Value Or Nothing Then
If c.Value.ToString().ToLower().Contains(strFilter) Then
containStr = True
Exit While
End If
End If
j = j + 1
End While
If Not containStr Then
datagridview.Rows.RemoveAt(i)
End If
i = i + 1
End While
End Sub
Your big problem is that you're removing items in the DataGridViewRowCollection as you're iterating through that collection. Even if you're not getting an 'index out of range' error doing this you're going to end up removing the wrong row(s) as the index value of later rows change when you remove earlier rows.
What you should do is instead of removing rows in your row loop, add the row's index to a List(Of Integers).
After you're done iterating through all the rows in your DataGridView, Reverse() your list and use the row index values in your List to remove rows via the RemoveAt() method.
Here's what I mean:
Private Sub PassFilter(ByRef datagridview As DataGridView, ByVal strFilter As String)
Dim i As Integer = 0
Dim j As Integer = 0
Dim containStr As Boolean = False
' Row indexes we'll remove later on.
Dim deleteIndexList As List(Of Integer) = New List(Of Integer)
While i < datagridview.Rows.Count
j = 0
containStr = False
'If all cells in a row does not contain strFilter, delete this row from datagridview
While j < datagridview.Rows(i).Cells.Count
Dim c As DataGridViewCell = datagridview.Rows(i).Cells(j)
' Note: you'll want to enclose the tests for DBNull.Value and Nothing in parens like I show here.
If Not (c.Value Is DBNull.Value And c.Value Is Nothing) Then
If c.Value.ToString().ToLower().Contains(strFilter) Then
containStr = True
Exit While
End If
End If
j = j + 1
End While
If Not containStr Then
' Don't remove rows here or your row indexes will get out of whack!
' datagridview.Rows.RemoveAt(i)
deleteIndexList.Add(i)
End If
i = i + 1
End While
' Remove rows by reversed row index order (highest removed first) to keep the indexes in whack.
deleteIndexList.Reverse()
For Each idx As Integer In deleteIndexList
datagridview.Rows.RemoveAt(idx)
Next
End Sub
Are you displaying the data as read-only, or for edit?
If you're allowing the users to edit, can you find some way to hide the rows you don't want shown, rather than trying to remove them?
If you're displaying this as read-only, you could grab the data after the filtering, and throw it into a new datagridview.... (ugly, yes, but a possible option)
Oh wait... what about if you pass the datagridview by value instead of reference, so your changes at remove will be maintained?