如何在离开行时使datagridview自动保存记录

时间:2010-07-20 08:46:58

标签: c# winforms datagridview

我有datagridview我想在编辑这条记录后自动保存每条记录。

3 个答案:

答案 0 :(得分:4)

有一个适合此事件的RowValidated事件。然后,您可以将值从网格中拉出并填充数据库命令。

答案 1 :(得分:1)

以下对我来说很好:

 ' ListChanged event is called whenever binding or datatable changes
Private Sub ProjectBindingSource_ListChanged(sender As Object, e As ListChangedEventArgs) Handles ProjectBindingSource.ListChanged

    Select Case e.ListChangedType
        ' Only update when listchanges are of following types
        Case ListChangedType.ItemChanged, ListChangedType.ItemAdded, ListChangedType.ItemDeleted
            Try
                'Update method will select the required update/insert/delete sql according to the tableadapter settings,
                'after successful update, it will accept changes in the dataset and change status of all rows back to unchanged
                Me.ProjectTableAdapter.Update(Me.StuklijstDataSet.Project)

            Catch ex As Exception
                ' exceptions will bounce back from the server,
                ' this will handle all possible data problems: concurrency, foreign key constraints, null not allowed, ... ;
                ' the update method (see above) will also mark the row with an ErrorProvider icon and tooltip with the error message

                ' if update is unsuccessful, roll back changes to the datatable
                Me.StuklijstDataSet.Project.RejectChanges()

                ' resetbindings to sort out problems with the control when rolling back adding or deleting records
                Me.ProjectBindingSource.ResetBindings(False)
            End Try

    End Select

End Sub

在加载数据表期间,事件仅提升3-4次,并且Listchangedtype的检查非常快(<1 ms)。 bindingsource有一个RaiseListChangedEvents属性,可以将其设置为False以临时转换ListChanged事件,但这似乎会导致填充数据表时出现问题。我相信不需要打开/关闭事件。

来自服务器的错误消息不是非常用户友好。 通过将异常作为SqlException对象读取,检索SQL错误代码,并将ErrorProvider消息更改为更为实际的文本,可以扩展上述方法。

答案 2 :(得分:0)