从datagridview更新行 [英] Updating row from datagridview
问题描述
您好,
有人可以举例说明如何通过文本框更新datagridview中的选定行。我正在使用访问数据库。谢谢。
Can someone could give me an example how to update selected row in datagridview via textbox. I'm using access database. Thank you.
推荐答案
如果DataGridView将其DataSource设置为表示DataTable,则考虑创建一个BindingSource,将BindingSource.DataSource设置为DataTable。然后将BindingSource设置为DataGridView的DataSource。
If the DataGridView has it's DataSource set to say a DataTable then consider creating a BindingSource, set the BindingSource.DataSource to a DataTable. The BindingSource is then set to the DataSource of the DataGridView.
获取当前DataGridView行所代表的当前DataRow。
To get the current DataRow represented by the current DataGridView row.
Dim row As DataRow = CType(SomeBindingSource.Current,DataRowView).Row
Dim row As DataRow = CType(SomeBindingSource.Current,DataRowView).Row
您现在可以访问该行。访问行中的字段。
You now have access to the row. To get access to a field in the row.
row.Field(Of String)(" FirstName")
row.Field(Of String)("FirstName")
请注意我推荐的原因以上是你指出的"更新"这让我觉得你是从ms访问表中获取数据。如果是这样你需要主键,当你将数据读入DataTable时你可以a)在
DataGridView中分配列而不是主键,但仍然可以通过BindingSource的想法获得键。
Note the reason I recommend the above is you indicated "update" which leads me to think you are obtaining data from a ms-access table. If so you would need to primary key which when reading data into a DataTable you can a) assign columns in the DataGridView but not for the primary key yet can still get the key via the BindingSource idea.
再次是从数据库中读取的情况(有很多方法)你只需写一个
UPDATE 语句并在命令对象上执行ExecuteNonQuery,或者如果使用TableAdapters,请按下保存按钮或任何有意义的内容。
Again being the case you read from the database (and there are many ways) you simply write a UPDATE statement and execute ExecuteNonQuery on the command object or if using TableAdapters press the save button or whatever makes sense.
我有
a demo 。该演示展示了我上面写的所有内容以及更多内容。
I have a demo over on Microsoft's code site. The demo shows all I have written above and more.
这篇关于从datagridview更新行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!