很简单的一段测试代码:
DataTable t;
private void Form1_Load(object sender, EventArgs e)
{
t = new DataTable();
t.Columns.Add("aaa", typeof(string));
t.Columns.Add("bbb", typeof(string)); DataRow r = t.NewRow();
r["aaa"] = "ffffff";
r["bbb"] = "aaaaa";
t.Rows.Add(r); textBox1.DataBindings.Add("Text", t, "aaa");
textBox2.DataBindings.Add("Text", t, "aaa"); dataGridView1.DataSource = t;
} private void button1_Click(object sender, EventArgs e)
{
//textBox2.DataBindings["Text"].ReadValue();
//textBox1.DataBindings["Text"].WriteValue();
t.Rows[0][0] = "cccc";
}
-----------------------------------------------
1.当textBox1变化时,textBox2没有跟着变化
2.当网格单元格变化时,文本框也没跟着变化
3.当点击按钮直接赋值时,所有绑定控件都变化了
4.当用ReadValue显示读取时,能够改变控件值
-----------------------------------------------
测试表明,改变控件值,DataTable中的值实际上是改变了的,就是没有反映到其他绑定控件上,这个问题怎么解决呢?
绑定的目的就是要让几个控件同步变化,如果要显示调用ReadValue,貌似没什么意义了。
DataTable t;
private void Form1_Load(object sender, EventArgs e)
{
t = new DataTable();
t.Columns.Add("aaa", typeof(string));
t.Columns.Add("bbb", typeof(string)); DataRow r = t.NewRow();
r["aaa"] = "ffffff";
r["bbb"] = "aaaaa";
t.Rows.Add(r); textBox1.DataBindings.Add("Text", t, "aaa");
textBox2.DataBindings.Add("Text", t, "aaa"); dataGridView1.DataSource = t;
} private void button1_Click(object sender, EventArgs e)
{
//textBox2.DataBindings["Text"].ReadValue();
//textBox1.DataBindings["Text"].WriteValue();
t.Rows[0][0] = "cccc";
}
-----------------------------------------------
1.当textBox1变化时,textBox2没有跟着变化
2.当网格单元格变化时,文本框也没跟着变化
3.当点击按钮直接赋值时,所有绑定控件都变化了
4.当用ReadValue显示读取时,能够改变控件值
-----------------------------------------------
测试表明,改变控件值,DataTable中的值实际上是改变了的,就是没有反映到其他绑定控件上,这个问题怎么解决呢?
绑定的目的就是要让几个控件同步变化,如果要显示调用ReadValue,貌似没什么意义了。
1、当TextBox的text修改后,DataTable没有接受修改,需要增加t.AcceptChanges();
2、如果DataTable有多个DataRow,需要指定绑定的行 DataTable t; public Form1()
{
InitializeComponent(); t = new DataTable();
t.Columns.Add("aaa", typeof(string));
t.Columns.Add("bbb", typeof(string)); DataRow r = t.NewRow();
r["aaa"] = "ffffff";
r["bbb"] = "aaaaa";
t.Rows.Add(r); textBox1.DataBindings.Add("Text", t, "aaa");
textBox2.DataBindings.Add("Text", t, "aaa"); } private void button1_Click(object sender, EventArgs e)
{
t.Rows[0][0] = "cccc"; } private void button2_Click(object sender, EventArgs e)
{
t.AcceptChanges();
}
private void Form3_Load(object sender, EventArgs e)
{
t = new DataTable();
t.Columns.Add("aaa", typeof(string));
t.Columns.Add("bbb", typeof(string)); DataRow r = t.NewRow();
r["aaa"] = "ffffff";
r["bbb"] = "aaaaa";
t.Rows.Add(r); textBox1.DataBindings.Add("Text", t, "aaa");
textBox2.DataBindings.Add("Text", t, "aaa");
dataGridView1.DataSource = t;
} private void button1_Click(object sender, EventArgs e)
{
t.AcceptChanges();
t.Rows[0][0] = "cccc";
}