Binding DataRow to TextBox
I want to bind textbox to single DataRow object (passed to dialog form for editing). Here is my code:
DataRow row = myDataTable.NewRow();
EditForm form = new EditForm(row);
//in EditForm constructor
nameTextBox.DataBindings.Add("Text", row, "name");
and I'm gettinh an error: Cannot bind to property or column in DataSource. Do you know what I'm missing or any workarounds maybe?
[Added]
My DataTable for sure contains DataColumn with ColumnName="name". Here is my code for creating DataTable
public DataTable SelectReturnDataTable(string tableName, string sql, params SQLiteParameter[] parameters)
{
开发者_开发知识库using (SQLiteConnection conn = new SQLiteConnection(_connectionString))
{
using (SQLiteCommand cmd = new SQLiteCommand(conn))
{
cmd.CommandText = sql;
foreach (SQLiteParameter p in parameters)
cmd.Parameters.Add(p);
SQLiteDataAdapter da = new SQLiteDataAdapter(cmd);
DataTable dt = new DataTable(tableName);
conn.Open();
da.Fill(dt);
return dt;
}
}
}
Try this:
DataView dv = myDataTable.DefaultView;
dv.RowFilter = "id=1";
nameTextBox.DataBindings.Add("Text",dv,"NAME");
I tried to reproduce this (with VS 2008 SP1), and I get an InvalidCastException if the row has null data in the name column, but the program continues and works.
In order to get the same exception as you, I have to make a mistake in the column name when binding. So I feel compelled to repeat @Henk's question, or ask that you show how you create the DataTable.
There's an overload for creating a DataBinding which takes in an object to use in case the source object is DBNull. You might want to try that.
精彩评论