开始以前,先认识一下WinForm控件数据绑定的两种形式,简单数据绑定和复杂数据绑定。
1. 简单的数据绑定
例1
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["connStr"].ToString()))
{
SqlDataAdapter sda = new SqlDataAdapter("Select * From T_Class Where F_Type='Product' order by F_RootID,F_Orders", conn);
DataSet Ds = new DataSet();
sda.Fill(Ds, "T_Class");
//使用DataSet绑定时,必须同时指明DateMember
this.dataGridView1.DataSource = Ds;
this.dataGridView1.DataMember = "T_Class";
//也可以直接用DataTable来绑定
this.dataGridView1.DataSource = Ds.Tables["T_Class"];
}
简单的数据绑定是将用户控件的某一个属性绑定至某一个类型实例上的某一属性。
采用如下形式进行绑定:引用控件.DataBindings.Add("控件属性", 实例对象, "属性名", true);
例2
从数据库中把数据读出来放到一个数据集中,比如List<>、DataTable,DataSet,我一般用List<>,
然后绑定数据源:
IList sList=StudentDB.GetAllList();
DataGridView.DataSource=sList;
如果你没有设置DataGridView的列,它会自动生成所有列。
2. 复杂数据绑定
复杂的数据绑定是将一个以列表为基础的用户控件(例如:ComboBox、ListBox、ErrorProvider、DataGridView等控件)绑定至一个数据对象的列表。
基本上,Windows Forms的复杂数据绑定允许绑定至支持IList接口的数据列表。此外,如果想通过一个BindingSource组件进行绑定,还可以绑定至一个支持IEnumerable接口的数据列表。
对于复杂数据绑定,常用的数据源类型有(代码以DataGridView作为示例控件)。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections;
namespace DataGridViewBindingData
{