ufancha ufancha - 1 year ago 54
Vb.net Question

How to get column ("id") value from datagridview with visual basic .net

I have a datagridview which displays data from database. on every row i have added a button with text value "Approve". when the user clicks on that button, i want the approved column on the database to be changed from 0 to 1. my question is how do i know which button on which row is clicked. like,

"UPDATE request SET approved=1 WHERE ID=???"
. and i don't want to show the auto increment ID column on the datagridview to the user.

Answer Source

This should give you a general idea. It uses SQLite but you can sub any db. I also used a generic index column name for the DGV. You can leave out the confirmation dialog, too, of course.

Private Sub Mydgv_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles Mydgv.CellContentClick
    If TypeOf DirectCast(sender, DataGridView).Columns(e.ColumnIndex) Is DataGridViewButtonColumn AndAlso e.RowIndex >= 0 Then
        Select Case e.ColumnIndex
            Case Mydgv.Columns("ApproveButton_Col_Name").Index
                Dim dr As DialogResult = MessageBox.Show("Are you sure you want to approve this?", "Confirm Approval", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
                If dr = Windows.Forms.DialogResult.Yes Then
                    Dim cmd As SQLiteCommand = conData.CreateCommand
                    cmd.CommandText = "Update request set Approved = 1 WHERE ID = " & CInt(Mydgv.Rows(e.RowIndex).Cells("MyIndex_Col_Name").Value)
                    Dim rst As Integer
                    rst = cmd.ExecuteNonQuery()
                    If rst <> 0 Then
                    End If
                End If
        End Select
    End If

End Sub