C# 将文本框绑定到 DataTable 的特定行
我正在构建一个简单的 C# 应用程序,允许用户编辑数据库中表的行。界面非常简单,基本上是一个行列表和几个按钮。选择一行并按“添加”按钮会弹出一个新表单,其中每列都有文本框。我希望用所选行的值填充这些列。
阅读了几篇文章后,我发现最简单的方法是将 TextBox 的 Text 属性绑定到 DataSource。因此,我将数据库中的值存储在 DataTable 对象中,并计划检索选定的 DataRow 并将其绑定到 TextBox。这是我使用的行:
productNameTextBox.DataBindings.Add(new Binding("Text", productRow, "Name"));
结果是以下异常:
类型的第一次机会异常 “System.ArgumentException”发生在 System.Windows.Forms.dll 无法绑定 到属性或列名称 数据源。参数名称:dataMember
是的,“名称”列确实存在。
根据绑定文档(http://msdn.microsoft.com/en-us/library/4wkkxwcz(v=VS.80).aspx)和许多示例阅读后,在我看来,必须绑定到该行所在的 DataTable。以下代码对我有用:
productNameTextBox.DataBindings.Add(new Binding("Text", productRow.Table, "Name"));
除了它总是将 TextBox 的值设置为第一行。如何指定要使用哪一行?
I am building a simple C# application that allows the user to edit the rows of a table in a database. The interface is very simple, it is basically a list of rows and a few buttons. Selecting a row and pressing the "Add" button pops up a new form with text boxes for each column. I want those columns to be populated with the values for the selected row.
After reading a few articles, I found that probably the simples way to do this is to bind the Text property of the TextBox to a DataSource. So I store the values from the database in a DataTable object, with the plan of retrieving the selected DataRow and binding its to the TextBox. This is the line I use:
productNameTextBox.DataBindings.Add(new Binding("Text", productRow, "Name"));
The result is the following exception:
A first chance exception of type
'System.ArgumentException' occurred in
System.Windows.Forms.dll Cannot bind
to the property or column Name on the
DataSource. Parameter name: dataMember
And yes, the "Name" column does exist.
After reading according to the documentation of bindings (http://msdn.microsoft.com/en-us/library/4wkkxwcz(v=VS.80).aspx) and many examples, it seems to me that one has to bind to the DataTable that the row is contained in. The following code worked for me:
productNameTextBox.DataBindings.Add(new Binding("Text", productRow.Table, "Name"));
Except it always sets the value of the TextBox to the first row. How do I specify which row to use?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用从 DataView 获取的 DataRowView,而不是行。 Iirc 这是通过 ICustomTypeDescriptor 配置为灵活(自定义)绑定的。
Rather than the row, use the DataRowView that you obtain from a DataView. Iirc this is configured for flexible (custom) binding, via ICustomTypeDescriptor.