简体   繁体   English

如何使用Visual Basic .net从Datagridview获取列(“ id”)值

[英]How to get column (“id”) value from datagridview with visual basic .net

I have a datagridview which displays data from database. 我有一个datagridview显示数据库中的数据。 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. 当用户单击该按钮时,我希望数据库上的批准列从0更改为1。我的问题是我如何知道单击了哪一行的哪个按钮。 like, "UPDATE request SET approved=1 WHERE ID=???" 例如, "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. 而且我不想在datagridview上向用户显示自动增量ID列。

This should give you a general idea. 这应该给您一个总体思路。 It uses SQLite but you can sub any db. 它使用SQLite,但您可以为任何数据库创建子目录。 I also used a generic index column name for the DGV. 我还为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
                        'success
                    Else
                        'failure
                    End If
                End If
        End Select
    End If

End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM