Getting row number in a DataGridView - vb.net

How do you get row number DataGridView cell? Specifically, if a user has selected a single cell, how can you get that row number? It needs to access a particular cell based on what the user has selected.
I know that the RemoveAt method can be used to remove at the Focus, but you cannot get the row number at focus apparently?
Thanks for the help!

You can simply use RowIndex on the current cell:
var row = dataGridView1.CurrentCell.RowIndex;

this one works fine .
Private Sub DataGridView1_RowPrePaint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewRowPrePaintEventArgs) Handles DataGridView1.RowPrePaint
If e.RowIndex >= 0 Then
Me.DataGridView1.Rows(e.RowIndex).Cells(0).Value = e.RowIndex + 1
End If
End Sub

It is nearly the same but you may also use this solution:
var row = dataGridView1.CurrentRow.Index

Another way if you need to track user interaction with a DataGridView:
In my case there is extra processing in some generic functions that use the Me.I_SelCol and Me.I_SelRow column and row coordinates, but I haven't shown that because it's not relevant to the OP.
Best regards,
Rob
Private Sub I_DataGridView_CurrentCellChanged(sender As Object, e As EventArgs) Handles I_DataGridView.CurrentCellChanged
If Me.I_DataGridView.CurrentCellAddress.X < 0 Or Me.I_DataGridView.CurrentCellAddress.Y < 0 Then Exit Sub
' The Windows Me.I_DataGridView object will have already deselected the current cell and selected the
' new cell as per user navigation using mouse or cursor keys. We just need to store the current
' co-ordinates for the currently selected cell.
Me.I_SelCol = Me.I_DataGridView.CurrentCellAddress.X
Me.I_SelRow = Me.I_DataGridView.CurrentCellAddress.Y
Exit Sub

If you in event procedure of datagridview you will found "e As DataGridViewCellEventArgs" you can get row number with e.RowIndex and column number with e.ColumnIndex
Private Sub myDGV_CellLeave(sender As Object, e As DataGridViewCellEventArgs) Handles myDGV.CellLeave
Dim myRow As Integer = e.RowIndex
End Sub
And if you in normal procedure you can get row number like this:
Private Sub btnGetRow_Click(sender As Object, e As EventArgs) Handles btnGetRow.Click
dim myRow1 as Integer = 0
dim myRow2 as Integer = 0
myRow1 = myDGV.CurrentCell.RowIndex
myRow2 = myDGV.CurrentRow.Index
End Sub

Related

How to pass the 2nd selected row in datagridview to textbox?

How do i pass my 2nd selected row in datagridview to textboxt. I only know how to put the first data. How do i pass the 2nd selected to textbox?
Dim i As Integer
i = DataGridView2.SelectedRows(0).Index
Me.txtEmployeeID.Text = DataGridView2.Item(0, i).Value
you can use this code it worked for me
Dim test As String = DataGridView1.SelectedRows(0).Cells(2).Value.ToString
You need to only change the .cell(Here write the index value of the cell)
Then you can use the string value to fill up textbox
Try using the following:
Dim secondRow as integer = 0
Private Sub DataGridView2_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView2.CellClick
'assuming that by second selected row, you mean the row after the selected row
secondRow = e.RowIndex + 1
End Sub
Private Sub RowToTextBox()
Try
For i = 0 to DataGridView2.ColumnCount - 1
txtEmployeeID.Text &= DataGridView2.Item(i, secondRow)
Next
Catch ex as Exception
MsgBox("You have selected the final row")
End Try
End Sub
I don't think Me. is needed when referring to a textbox in the same form.
Since you don't know how many rows your user will select, I think looping thought the SelectedRows collection might work. I used the Name column because that is what I happened to have in my grid. Instead of a MessageBox you could add the values to a ListBox.
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
For Each GridRow As DataGridViewRow In DataGridView1.SelectedRows
MessageBox.Show($"Value is {GridRow.Cells("Name").Value}")
Next
End Sub

Hide rows if column contains particular text/ string

I have a datagridview wich I have no bound datasource too I also have a button and three rows in my datagridview. If my column named STATUS contains the word CLOSED I would like to hide that entire row but i dont want to delete it just hide it.
If anyone woyuld like to know I am ussing VB.net
How can I do this?
If you are using a bound datasource you want to capture the DataGridView.DataSourceChanged event.
Would look like this.
Private Sub DataGridView1_DataSourceChanged(sender As Object, e As System.EventArgs) Handles DataGridView1.DataSourceChanged
For Each row As DataGridViewRow In DirectCast(sender, DataGridView).Rows
If row.Cells("status").Value.ToString.ToLower.Contains("Closed") Then
row.Visible = False
End If
Next
End Sub
If you are not using a datasource you would want to capture the DataGridView.RowsAdded event.
Would look like this.
Private Sub DataGridView1_RowsAdded(sender As Object, e As System.Windows.Forms.DataGridViewRowsAddedEventArgs) Handles DataGridView1.RowsAdded
Dim dg As DataGridView = sender
If dg.Columns.Count > 0 And e.RowIndex <> 0 Then
Dim theRow As DataGridViewRow = dg.Rows(e.RowIndex)
If theRow.Cells("status").Value.ToString.ToLower.Contains("closed") Then
theRow.Visible = False
End If
End If
End Sub

Deleting a record from the datagridview

In VB2012, I have a created a student management software with SQL2012 as the back-end. The below code is used for deleting a selected record from the datagridview when DELETE button is clicked:
Private Sub Delete_Click(sender As Object, e As EventArgs) Handles Delete.Click
Dim DelStudent As StudentDataSet1._masterRow
DelStudent= CType(CType(StudentmasterBindingSource.Current, DataRowView).Row, StudentDataSet1.Student_masterRow)
DelStudent.Delete()
Me.Validate()
Me.StudentmasterBindingSource.EndEdit()
Me.Student_masterTableAdapter.Update(StudentDataSet1.Student_master)
End Sub
But instead of the selected row being deleted, the first row gets deleted. Please help...
Selected row is not necessary current, from the perspective of binding source. You need to be using DataGridView.SelectedRows. Each is a DataGridViewRow, and you should be able to retrieve DataGridViewRow.DataBoundItem, cast it to DataRow, and use Delete on that.
the code below is also helpful
Private Sub btnRemoveItem_Click(sender As Object, e As EventArgs) Handles btnRemoveItem.Click
If datagridviewname.SelectedRows.Count > 0 Then
For i As Integer = datagridviewname.SelectedRows.Count - 1 To 0 Step -1
datagridviewname.Rows.RemoveAt(datagridviewname.SelectedRows(i).Index)
Next
Else
MessageBox.Show("Select Row to remove")
End If
End Sub

get value of selected item in second column... returning previous item

I get that there are other questions like this, but for some reason nobody seems to have this problem. I'm trying to populate a 2 column listview that I create on load like this.
With lstShipMethods
.View = View.Details
.FullRowSelect = True
.HeaderStyle = ColumnHeaderStyle.None ' set to whatever you need
.Columns.Clear() ' make sure collumnscollection is empty
' Add 3 columns
.Columns.AddRange(New ColumnHeader() {New ColumnHeader(), New ColumnHeader()})
End With
lstShipMethods.Items.Add(New ListViewItem({"col1data", "col2data1"}))
lstShipMethods.Items.Add(New ListViewItem({"col1data", "col2data2"}))
It populates just fine, but when I try to get the data from the selected items column like this
Private Sub lstShipMethods_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lstShipMethods.SelectedIndexChanged
Dim val As String = lstShipMethods.FocusedItem.SubItems(1).Text
MessageBox.Show(val)
End Sub
after the first click it will always show both values aka second column from row one and row two will be output in the MessageBox.
You can use the ItemSelectionChanged event instead.
Private Sub lstShipMethods_SelectedIndexChanged(sender As System.Object, e As ListViewItemSelectionChangedEventArgs) Handles lstShipMethods.ItemSelectionChanged
If e.IsSelected Then
Dim val As String = lstShipMethods.FocusedItem.SubItems(1).Text
MessageBox.Show(val)
End If
End Sub

Capturing value of DataGridView CheckBox in VB.Net

I have a datagridview (unbound). Fields are Name, Family Name and Phone No and a checkbox colum.
There are ten rows in that DataGridView.
There is an OK button
I need to get message of showing which rows user has checked. The message should appear when user clicks on the OK button. There could be several messages, checking each row one by one, in a loop.
I am not able to get this message. I tried following code in OK button :
Dim strCB As String = dgvChooseQs.Rows(0).Cells(3).Value.ToString
Cell(3) is my checkbox. Do not consider Rows(0), at the moment I am just checking value at row 0
Thanks for your help.
Furqan
Do not use the cell index. Your checkbox column must have a name so you should use it.
Otherwise, what you want to do would be something like this
For each oRow as DataGridViewRow in dgvChooseQs.Rows
If oRow.Cells("ColNamE").Value = True then
'do whatever you need to do.
End if
Next
If you feel you need to cast the column, then you can use CType, but the type is DataGridViewCheckBoxCell, not CheckBox.
You need to do something like this:
if ctype(dgvChooseQs.Rows(0).findcontrol("whateverYourCheckBoxIsNamed"), checkbox).checked then
'throw the message
end if
You may cast the cell value to Boolean, and then check it, as follows:
Dim RowIndex As Integer = ...
Dim ColumnIndex As Integer = ...
Dim IsTicked As Boolean = CBool(DataGridView1.Rows(RowIndex).Cells(ColumnIndex).Value)
If IsTicked Then
MessageBox.Show("You ticked the box.")
Else
MessageBox.Show("You cleared the box.")
End If
Only the third example worked for me but I had to add a Timer
Private Sub DgvElencoFile_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles DgvElencoFile.CellClick
'Variabili gestione programma
Dim numerocolonnaSelezionata As Integer
Dim numeroColonnaSelezionataPerDowonload As Integer
Dim numeroRigaSelezionata As Integer
numeroRigaSelezionata = e.RowIndex
NumerocolonnaSelezionata = e.ColumnIndex
If NumeroRigaSelezionata < 0 Then
ClaFunzSgnSon.SegnaleSonoro(ClaFunzSgnSon.EnTipoSgnSon.ErroreImpostazioneDati)
GoTo FineSubFunz
End If
numeroColonnaSelezionataPerDowonload = -1
If DgvElencoFile.Rows(numeroRigaSelezionata).Cells(ClnDownLoad.Name).Selected Then numeroColonnaSelezionataPerDowonload = numerocolonnaSelezionata
If numeroColonnaSelezionataPerDowonload >= 0 Then
TimVisCheckDownLoad.Start()
End If
FineSubFunz:
End Sub
Private Sub TimVisCheckDownLoad_Tick(sender As Object, e As EventArgs) Handles TimVisCheckDownLoad.Tick
TimVisCheckDownLoad.Stop()
Dim isTickedOn = CBool(DirectCast(DgvElencoFile.CurrentCell, DataGridViewCheckBoxCell).EditingCellFormattedValue)
If isTickedOn Then
MessageBox.Show("You ticked the box.")
Else
MessageBox.Show("You cleared the box.")
End If
End Sub
I found a simple solution.
Just change the cell focus after click on cell.
Private Sub DGV_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DGV.CellContentClick
If e.ColumnIndex = "Here checkbox column id or name" Then
DGV.Item(e.ColumnIndex, e.RowIndex + 1).Selected = True
'Here your code
MsgBox DGV.Item(e.ColumnIndex, e.RowIndex).Value
End If
End Sub
Don't forget to check if the column of your (ckeckbox + 1) index exist.
Set type of grid in dataGridView to 'DataGridViewCheckBoxXColumn' instead of DataGridViewCheckBoxColumn.
all problems will be solved
The post is old but it can help in need:
You have these three properties after casting your cell:
Private Sub YourDataGridView_CellMouseClick(sender As Object, e As DataGridViewCellMouseEventArgs) Handles YourDataGridView.CellMouseClick
Dim b, b1, b2 As Boolean
b = DirectCast(YourDataGridView.CurrentCell, DataGridViewCheckBoxCell).EditingCellValueChanged
b1 = CBool(DirectCast(YourDataGridView.CurrentCell, DataGridViewCheckBoxCell).EditingCellFormattedValue)
b2 = CBool(DirectCast(YourDataGridView.CurrentCell, DataGridViewCheckBoxCell).EditedFormattedValue)
End Sub
it's a long time since this question was sent, but can be useful this answer to anybody with the same issue. In my case, I used (I'm using your notation):
dgvChooseQs.Item(6, vCont).State
where 6 is the checkbox column number, in my case column 6. vCont is an iteration counter in a FOR NEXT loop. If State equals 32, checkbox was checked, else State will be zero. I hope this can be of help.