C# Bind TextBox To Specific Row Of DataTable

bindingcdatarowdatatabletextbox

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?

Best Answer

Rather than the row, use the DataRowView that you obtain from a DataView. Iirc this is configured for flexible (custom) binding, via ICustomTypeDescriptor.

Related Topic