日期:2014-05-17  浏览次数:21081 次

如何通过bindingnavigator修改当前行的某字段值?
近来搞winform开发的, 我通过bindingnavigator绑定到一个bindingsource, bindingsource绑定到dataset1["table1"],,然后用到了 OleDbDataAdapter Adapter1;
OleDbCommandBuilder CommandBuilder1;
目前是能够查询到数据了。
假设里面有字段"f4"。。。现在我想更新bindingnavigator的当前行的字段"f4" = textbox1.text;该怎么写?主要是如何获取当前行的序号i,这样我就可以用以下语句搞定了。
dataset1["table1"].rows[i]["f4"]= textbox1.text; 
Adapter1.Update(dataSet1, "table1");

------解决方案--------------------
你可以试试这个代码生成工具,里面包含示例,生成的VS项目文件里,有你所问的问题。
http://download.csdn.net/detail/cwbugs/4067125
------解决方案--------------------
都不用bindingnavigator,
------解决方案--------------------
BindingNavigator只是绑定到BindingSource的一个导航条控件,其自身不存在“当前行”
通常的做法是通过绑定到BindingSource的数据显示控件进行更改,最常见的就是DataGridView了

其当前行号:DataGridView.CurrentCellAddress.Y
dataGridView1.Rows[dataGridView1.CurrentCellAddress.Y].Cells["f4"].Value = textbox1.text
或者:dataGridView1.CurrentCell.Value = textbox1.text

但不能使用CurrentCellAddress直接对DataSet或DataTable进行赋值,因为DataGridView可能进行了筛选或排序,其单元格的位置索引可能和DataTable内的不一致
------解决方案--------------------
不废话,直接上代码
DataRowView drv = personBindingSource.Current as DataRowView;
drv["personId"].ToString()

------解决方案--------------------
DataRowView drv = personBindingSource.Current as DataRowView;
drv["personID"].tostring()="1234567890";
------解决方案--------------------
奇怪了,我发的怎么失踪了
------解决方案--------------------
BindingNavigator只是绑定到BindingSource的一个导航工具栏控件,其本身没有“当前行”
BindingSource有当前行属性,但不常用

类似楼主这种情况,通常使用与BindingSource绑定的数据显示控件进行定位和更新,最常见的即是DataGridVeiw
其当前行索引:DataGridView.CurrentCellAddress.Y
dataGridView1.Rows[dataGridView1.CurrentCellAddress.Y].Cells["f4"].Value = textbox1.text
或者直接:dataGridView1.CurrentCell.Value = textbox1.text

但不可以直接使用CurrentCellAddress来对DataSet或DataTable进行更新,因为DataGridView可能进行了筛选或排序,用户选定行的行号 与DataTable内 实际数据行的行号 可能不一致
------解决方案--------------------
补充一下
DataGridView绑定到BindingSource后,
dataGridView1.Rows[dataGridView1.CurrentCellAddress.Y].Cells["f4"].Value = textbox1.text
会自动更新到BindingSource对应的DataTable内
最后只要
Adapter1.Update(dataSet1)及dataSet1.AcceptChanges()就行了
------解决方案--------------------
探讨
因为我用不着DataGridView啊,所以而且那个需要更新的字段我又用不着显示出来。

------解决方案--------------------
上面的代码放在什么事件响应里了,可能EndEdit和Update得太早了,绑定的字段还没来得及上传更改
或者干脆所有字段都手动更新
((DataRowView)bindingSource1.Current).Row["字段1"] = "新值1";
((DataRowView)bindingSource1.Current).Row["字段2"] = "新值2";
...
------解决方案--------------------
这里的EndEdit和Update过早了。可以在它们的前面调用 TextBox 的 母容器(如Form)的Validate()方法,强制TextBox提交(或者其它方法。我未试过,不能保证)

或者去除这里的EndEdit和Update,放在Form_Closing里