如何在输入后更新datagridview中的单元格? vb.net

时间:2013-03-14 15:31:30

标签: vb.net sql-server-2008 data-binding datagridview keypress

我想要在输入单元格后从datagridview更新到sql。但它不起作用。

此代码:

Private Sub dgvShow_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles dgvShow.KeyPress

Dim sb3 As New StringBuilder
Dim da2 As New SqlDataAdapter

For i As Integer = 0 To dgvShow.Rows.Count - 2
            If dgvShow.Rows(i).Cells(0).Value IsNot Nothing Then
                sb3.Remove(0, sb3.Length())
                sb3.Append("UPDATE PositionLevelWelfare ")
                sb3.Append("SET wfDivision=@wfDivision,wfSection=@wfSection,wfPosition=@wfPosition,wfBaht=@wfBaht")
                sb3.Append(" FROM PositionLevelWelfare pw")
                sb3.Append(" WHERE pw.Run=@Run")
                Dim SqlEdit As String = ""
                SqlEdit = sb3.ToString()

                da2.SelectCommand.CommandText = SqlEdit
                da2.SelectCommand.Parameters.Add("@Run", SqlDbType.NVarChar).Value = dgvShow.Rows(i).Cells(0).Value
                da2.SelectCommand.Parameters.Add("@wfDivision", SqlDbType.NVarChar).Value = dgvShow.Rows(i).Cells(1).Value
                da2.SelectCommand.Parameters.Add("@wfSection", SqlDbType.NVarChar).Value = dgvShow.Rows(i).Cells(2).Value
                da2.SelectCommand.Parameters.Add("@wfPosition", SqlDbType.NVarChar).Value = dgvShow.Rows(i).Cells(3).Value
                da2.SelectCommand.Parameters.Add("@wfBaht", SqlDbType.NVarChar).Value = dgvShow.Rows(i).Cells(4).Value
                da2.SelectCommand.ExecuteNonQuery()
                da2.SelectCommand.Parameters.Clear() 
            End If
        Next
End Sub

感谢您的旅行时间。 :)

1 个答案:

答案 0 :(得分:1)

您可以使用活动DataGridView.CellBeginEditDataGRidView.CellEndEdit 然后按Enter键后更新值,或者当您离开当前单元格时 >(单击其他单元格..)

DataGridView.CellBeginEdit

的处理程序中

在此处理程序中,我们只保存单元格的当前(旧)值 在此示例中,我使用DataGridView.Tag属性作为保存旧值的位置

Private Sub dgv_CellBeginEdit(sender As Object, e As DataGridViewCellCancelEventArgs) Handles dgv.CellBeginEdit
    If e.RowIndex < 0 OrElse e.ColumnIndex < 0 Then Exit Sub
    Me.dgv.Tag = Me.dgv.CurrentCell.Value
End Sub

然后在DataGRidView.CellEndEdit

的处理程序中
Private Sub dgv_CellEndEdit(sender As Object, e As DataGridViewCellEventArgs) Handles dgv.CellEndEdit

    'Here you will get a new value of cell from dgv.CurrentCell.Value and compare with old value from dgv.Tag
    'You can add your checks for new value if you need. If some check fails just set
    dgv.CurrentCell.Value = dgv.Tag
    'If checks succeed then run your update to Database function with new value


End Sub

或者您可以使用dgv.CellValidating事件,您可以根据需要使用支票查看新值和Cancel更改。然后在CellEndEdit jut中运行UpdateTodatabase函数 请记住CellValidating之前发生CellEndEdit

MSDN DataGridView.CellValidating Event