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"];
private void Form1_Load(object sender, EventArgs e)
//使用List<>泛型集合填充DataGridView
List<Student> students = new List<Student>();
Student hat = new Student("Hathaway", "12", "Male");
Student peter = new Student("Peter","14","Male");
Student dell = new Student("Dell","16","Male");
Student anne = new Student("Anne","19","Female");
students.Add(hat);
students.Add(peter);
students.Add(dell);
students.Add(anne);
this.dataGridView1.DataSource = students;
Dictionary<>泛型集合
private void Form1_Load(object sender, EventArgs e)
//使用Dictionary<>泛型集合填充DataGridView
Dictionary<String, Student> students = new Dictionary<String, Student>();
Student hat = new Student("Hathaway", "12", "Male");
Student peter = new Student("Peter","14","Male");
Student dell = new Student("Dell","16","Male");
Student anne = new Student("Anne","19","Female");
students.Add(hat.StuName,hat);
students.Add(peter.StuName,peter);
students.Add(dell.StuName,dell);
students.Add(anne.StuName,anne);
//在这里必须创建一个BindIngSource对象,用该对象接收Dictionary<>泛型集合的对象
BindingSource bs = new BindingSource();
//将泛型集合对象的值赋给BindingSourc对象的数据源
bs.DataSource = students.Values;
this.dataGridView1.DataSource = bs;
3.3 利用SqlDataReader填充DataGridView
//使用SqlDataReader填充DataGridView
using (SqlCommand command = new SqlCommand("select * from product", DBService.Conn))
SqlDataReader dr = command.ExecuteReader();
BindingSource bs = new BindingSource();
bs.DataSource = dr;
this.dataGridView1.DataSource = bs;
3.4 利用SqlDataAdapter对象向DataGridView中添加数据
using (SqlDataAdapter da = new SqlDataAdapter("select * from Product", DBService.Conn))
DataSet ds = new DataSet();
da.Fill(ds);
this.dataGridView1.DataSource = ds.Tables[0];