[转] C# TextBox、DataGrideView中的数据绑定

Xavierr 原文 C#数据绑定——简单的文本框绑定DataGridView

一、TextBox的数据绑定

经常写用一个TextBox显示某个对象,然后编辑之后再保存的程序。以前都是在TextBox_TextChanged事件中修改对象的值,或者保存的时候再读取TextBox.Text属性保存对象的值。这样比较麻烦,而且经常容易出错。后来了解了C#的数据绑定,发现能够很好的解决这个问题。

1. 首先C#的TextBox本身就带数据绑定功能。

下面的代码就是把_myData对象的"TheValue"属性绑定到textBox1和textBox2的"Text"属性。最后一个参数不同:

1)其中DataSourceUpdateMode.OnPropertyChanged表示textBox1.Text发生变化,_myData.TheValue也变化,叫双向绑定。

2)DataSourceUpdateMode.Never表示Text1.Text变化不影响_myData.TheValue的值,是单向绑定。

private void Form1_Load(object sender, EventArgs e)
{
_myData = new MyData();
textBox1.DataBindings.Add("Text", _myData, "TheValue", false, DataSourceUpdateMode.OnPropertyChanged);
textBox2.DataBindings.Add("Text", _myData, "TheValue", false, DataSourceUpdateMode.Never);
}

2.也许有人留意到了,为什么上面的叫"双向绑定"呢?如果_myData.TheValue的值变化了,两个文本框的Text会变化吗?不错,仅在 textBox上数据绑定还不叫双向绑定,对象数据变化要通知绑定该对象的控件才行。这样就需要对象实现INotifyPropertyChanged接 口。

public class MyData : INotifyPropertyChanged
{
private string _theValue = string.Empty; public string TheValue
{
get { return _theValue; }
set
{
if (string.IsNullOrEmpty(value) && value == _theValue)
return; _theValue = value;
NotifyPropertyChanged(() => TheValue);
}
} public event PropertyChangedEventHandler PropertyChanged; public void NotifyPropertyChanged<T>(Expression<Func<T>> property)
{
if (PropertyChanged == null)
return; var memberExpression = property.Body as MemberExpression;
if (memberExpression == null)
return; PropertyChanged.Invoke(this, new PropertyChangedEventArgs(memberExpression.Member.Name));
}
}

3.好了,数据绑定完成了,看看效果吧。textBox1.Text变化—>_myData.TheValue变化—>textBox2.Text变化。反过来textBox2.Text变化就不是这样了,因为textBox2使用的单向绑定。

[转] C# TextBox、DataGrideView中的数据绑定

二、DataGridView的数据绑定

没什么可说的,DataGridView可以绑定DataSet,也可以绑定DataTable。直接设置DataSource属性。

DataSet dataSet = new DataSet();
dataGridView1.DataSource = dataSet;
dataGridView1.DataSource = dataSet.Tables[0];

设置DataGridView的Column属性就可以决定哪一列显示的数据。

Column1.DataPropertyName = "ID"
上一篇:通用超级强大的基于Oracle数据库的代码生成器


下一篇:js-自定义事件