DataGridView:单元格值更改时更新SQL数据库

时间:2016-11-15 12:53:26

标签: vb.net winforms

我创建了一个包含DataGridView的表单,并创建了第一列作为复选框列,并且fullrowselect为True。
我希望当我单击行的复选框或更改所选行的复选框值时,应该在数据库中更新该特定记录...

我正确地编写了查询但遇到了下面提到的一些问题。

现在我首先尝试了单元格点击事件...

 Private Sub DGVHelp_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles DGVHelp.CellClick
    Try
        If PubHelpCode = "ACTMAST" And e.ColumnIndex = 0 Then 'if only checkbox column is clicked
            cmd = New SqlCommand("Update FAMPAR SET Tag = '" & DGVHelp(0, e.RowIndex).Value & "' where Account_Code = '" & DGVHelp(1, e.RowIndex).Value & "' ", con1)
            ExecuteQuery(con1, "EDITCHECKBOX") ' Its my UDF
            DGV_Reset()' This clears the datagrid and fetch the data again
        End If
    Catch ex As Exception
        MsgBox(ex.ToString)
    End Try
End Sub

当我单击复选框单元格(第一列)时,事件首先运行,然后更改单元格的值...即在单击过程事件期间,DGVHelp(0,e.RowIndex).Value不会如果勾选或未勾选,则更改其值。

我甚至尝试过cellvaluechanged活动,但它通过一些我不知道的连续过程来挂起程序......

我应该用哪个事件来完成我的任务?

如果有任何其他与此任务有关的意见/想法,那么请分享......

下面分享了Code OneDrive链接。
Solution Code link

2 个答案:

答案 0 :(得分:0)

在此问题中,更好的解决方案是使用DataGridView.CellMouseClick事件。只需单击任何单元格即可触发此事件。

Private Sub DataGridView1_CellMouseClick(sender as Object, e as DataGridViewCellMouseEventArgs) _ 
    Handles DataGridView1.CellMouseClick

    'todo

End Sub

答案 1 :(得分:0)

您必须使用DataGridView.CellValueChanged事件。这是在您的情况下使用的最佳事件。使用MouseClick事件不是一个好主意。

https://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.cellvaluechanged(v=vs.110).aspx

在事件子内部使用DataGridViewCellEventArgs属性e.columnIndex来检查编辑的colunn是否包含复选框。否则你必须检查你的代码。

  

在使用sqlcommand类

时最好使用Using子句
Using cmd as New SqlCommand("Update FAMPAR SET Tag = '" & DGVHelp(0, e.RowIndex).Value & "' where Account_Code = '" & DGVHelp(1, e.RowIndex).Value & "' ", con1)

        ExecuteQuery(con1, "EDITCHECKBOX") ' Its my UDF

End Using

编辑1:

检查完解决方案后。它不是那么清楚,但你可以做一些解决方法。

1-定义布尔变量m_BoolValueChanged

Private m_BoolValueChanged as Boolean = True

2-在DGVHelp_CellValueChanged Sub中使用此变量以防止无限循环。喜欢以下:

Private Sub DGVHelp_CellValueChanged(sender As Object, e As DataGridViewCellEventArgs) Handles DGVHelp.CellValueChanged
    Try
        If PubHelpCode = "ACTMAST" And e.ColumnIndex = 0 Then

            If m_BoolValueChanged Then

            m_BoolValueChanged = False


            cmd = New SqlCommand("Update FAMPAR SET Tag = '" & DGVHelp(0, e.RowIndex).Value & "' where Account_Code = '" & DGVHelp(1, e.RowIndex).Value & "' ", con1)
            ExecuteQuery(con1, "EDITCHECKBOX")
            Dim ri As Integer = DGVHelp.CurrentRow.Index
            DGV_Reset()
            DGVHelp.Rows(ri).Selected = True

            m_BoolValueChanged = False


            End If


        End If
    Catch ex As Exception
        MsgBox(ex.ToString)
    End Try
End Sub

你可能会找到更好的解决方案,但这会有所帮助

相关问题