现在的位置: 首页 > 综合 > 正文

WinForm下TextBox的数据绑定和更新

2012年03月14日 ⁄ 综合 ⁄ 共 1890字 ⁄ 字号 评论关闭

一直以来在Form上的TextBox要显示数据库内容,通常就是直接赋值。看了http://www.15seconds.com/issue/040908.htm上讲的要做对应类,现在来说,ORM没什么做的特别好的,所以这么做还是有些累。http://tech.ccidnet.com/pub/article/c1138_a9879_p1.html里面介绍也只是单向绑定,而且实现的不是很好。

于是就想直接将TextBox绑定到DataSet上。就做了下面的例子,用的是pubs库中authors表:

private void Form2_Load(object sender, System.EventArgs e)
{
 
this.sqlDataAdapter1.Fill(authorsNameSet);
 
this.dataGrid1.DataSource = authorsNameSet.Tables[0].DefaultView;
 
this.FillUIContent();
}

private void button1_Click(object sender, System.EventArgs e)
{
 index
++;
 
if(index > this.authorsNameSet.Tables[0].Rows.Count - 1)
 
{
  index 
= 0;
 }
 
 
this.FillUIContent();
}

private void FillUIContent()
{
 
if(this.textBox1.DataBindings["Text"!= null)
 
{
  
this.textBox1.DataBindings.Remove(this.textBox1.DataBindings["Text"]);
 }

 
this.textBox1.DataBindings.Add("Text", authorsNameSet.Tables[0].Rows[index]["au_fname"], "");

 
if(this.textBox2.DataBindings["Text"!= null)
 
{
  
this.textBox2.DataBindings.Remove(this.textBox2.DataBindings["Text"]);
 }

 
this.textBox2.DataBindings.Add("Text", authorsNameSet.Tables[0].Rows[index]["au_lname"], "");
}



上面的是单向绑定,就是说,也只能显示,不能更新回来。那要更新回来怎么办?我试了用TextChange事件。在Form_Load中间加上:

this.textBox1.TextChanged +=new EventHandler(textBox1_TextChanged);
this.textBox2.TextChanged +=new EventHandler(textBox2_TextChanged);

然后事件处理里面,加上

private void textBox1_TextChanged(object sender, System.EventArgs e)
{
 
this.authorsNameSet.Tables[0].Rows[index]["au_fname"= this.textBox1.Text;
 CurrencyManager cm 
= (CurrencyManager)this.dataGrid1.BindingContext[this.dataGrid1.DataSource];
 cm.Refresh();
}

private void textBox2_TextChanged(object sender, EventArgs e)
{
 
this.authorsNameSet.Tables[0].Rows[index]["au_lname"= this.textBox2.Text;
 CurrencyManager cm 
= (CurrencyManager)this.dataGrid1.BindingContext[this.dataGrid1.DataSource];
 cm.Refresh();
}

然后好了,就可以同步更新DataSet了。

然后呢,想做的好,干脆派生一个TextBox,加一个DataSource用来放数据集, DataMember属性用来放数据表加字段,封装更新的内容。(代码懒得写了)

抱歉!评论已关闭.