使用C#开发Windows数据库应用程序.ppt
文本预览下载声明
第8章使用C#开发Windows数据库应用程序 数据库原理及应用 * 第八章 简单数据绑订 复杂数据绑订 数据源的类型 DataGrid的使用 Windows应用程序开发实例 本章要点 8.1 数据绑定 数据绑定是指数据源元素与图形界面的接口技术,如使用TextBox控件绑定到表中的单个值。窗体控件可以按照 两种方式绑定数据:简单数据绑定和复杂数据绑定。 Windows数据绑定控件(如Label、Button或TextBox能够绑定数据,因为Binding类提供了这样的功能(System.Windows.Forms.Binding),这个类由.NET Framework提供,负责在每个控件属性和数据源中的数据元素之间创建简单的绑定。如: textBox1.DataBindings.Add(″Text″,da,″Employees.FirstName″); 控件的DataBindings属性可以使用Add方法添加其中的每个属性。Add方法有三个参数。第一个参数是控件属性的名称,如TextBox控件的Text属性或者DataGrid控件的DataSource属性。第二个参数是下列任意类,或者实现下列任意接口的类的实例,如表8-1列出几个接口及实现这些接口的类。 第三个参数描述数据源中的数据成员。它是必须能转化为标量值的字符串文字,如使用DataSet时要根据表名称所选的列。 表8-1 可用于Binding类构造函数的第二个参数的类 DataView,DataViewManager ITypedList DataSet,DataTable IListSource Array,BitArray ICollection 实现接口的一些类 接口 如果想显式声明Binding对象,则可以使用类似下面的代码,例如,想把TextBox控件的Text属性绑定到表中的数据元素上。 Binding newBind=new Binding(″Text″,ds,″Employees.FirstName″); textBox1.DataBindings.Add(newBind); 8.1.1 简单数据绑定 简单数据绑定是指每个控件属性与数据源的单一元素之间的一对一关系。下面的例子演示简单数据绑定,将一组 TextBox 控件上的 Text 属性绑定到作为客户列表存储的 Customer 对象的属性。在控件上使用 DataBindings 集合添加简单数据绑定。 textBoxID.DataBindings.Add(Text, custList, CustomerID); textBoxTitle.DataBindings.Add(Text, custList, ContactTitle); textBoxLastName.DataBindings.Add(Text, custList, ContactName); textBoxFirstName.DataBindings.Add(Text, custList, CompanyName); textBoxAddress.DataBindings.Add(Text, custList, Address); 每个TextBox.Text都绑定到当前 Customer 对象,如同 BindingContext 进行维护一样。若要更改当前对象,可使用 BindingContext 递增或递减集合的 Position 属性。 例如,通过按如下所示处理按钮的Click事件实现 Move Next 按钮。 private void buttonMoveNext_Click(object sender, System.EventArgs e) { this.BindingContext[custList].Position++; } 每当位置更改时,BindingContext 引发一个事件。 this.BindingContext[custList].PositionChanged += new System.EventHandler(customer_PositionChanged); private void customer_PositionChanged(object s
显示全部