使用SqlAdapter更新RadGridView绑定数据遇错及绑定疑问求助
问题解决方案
一、SqlDataAdapter.Update参数错误修复
1. 单个DataRow的正确更新方式
SqlDataAdapter的Update方法没有直接接受单个DataRow的重载,需将单个行包装成DataRow数组传入,匹配Update(dataRows As DataRow())重载:
adapter.Update(New DataRow() {lastEditRow})
2. 解决AmbiguousMatchException错误
传入DataSet时出现重载歧义,直接传入目标DataTable即可消除歧义:
adapter.Update(dsSolution.Tables("MyTable"))
3. 关键前提:配置CommandBuilder
你的SqlDataAdapter仅初始化了查询命令,缺失更新/插入/删除命令会导致Update执行失败。需添加SqlCommandBuilder自动生成这些命令:
' 在初始化adapter的模块中添加 Dim cmdBuilder As New SqlCommandBuilder(adapter)
二、BindingSource与RadGridView绑定的正确步骤
你的代码存在局部变量覆盖类成员的问题,修正后完整绑定逻辑如下:
- 确保类级别的
bindingSource被正确初始化:
Public Class definitionSolution Private lastEditRow As DataRow = Nothing Private bindingSource As BindingSource ' 类级成员,避免局部变量覆盖 Public Sub New() InitializeComponent() bindingSource = New BindingSource Dim dsSolution As New DataSet() adapter.Fill(dsSolution, "MyTable") bindingSource.DataSource = dsSolution.Tables("MyTable") ' DataTable绑定到BindingSource definitionView.DataSource = bindingSource ' BindingSource绑定到RadGridView AddHandler bindingSource.CurrentChanged, AddressOf DefinitionView_CurrentChanged End Sub
- 移除
Load事件中的重复填充逻辑,避免数据状态混乱:
Private Sub AutoSavingDataBSEventsForm_Load(ByVal sender As Object, ByVal e As EventArgs) Dim current As Object = bindingSource.Current If current IsNot Nothing Then Me.lastEditRow = (CType(current, DataRowView)).Row End If End Sub
此时BindingSource与RadGridView的绑定已完成,GridView的编辑操作会自动同步到关联的DataTable。
三、修正后的CurrentChanged事件代码
Private Sub DefinitionView_CurrentChanged(ByVal sender As Object, ByVal e As EventArgs) Dim currentView As DataRowView = TryCast(bindingSource.Current, DataRowView) If currentView Is Nothing Then Return Dim dataRow As DataRow = currentView.Row If lastEditRow IsNot Nothing AndAlso lastEditRow.RowState = DataRowState.Modified Then adapter.Update(New DataRow() {lastEditRow}) lastEditRow.AcceptChanges() ' 提交变更,避免重复更新 End If lastEditRow = dataRow End Sub
内容的提问来源于stack exchange,提问作者legends1337
相关产品推荐
相关产品推荐

