天天看點

向DataGridView控件添加資料

在Winform中向DataGridView控件添加資料很常用到,現總結3種填充DataGridView方法:

1.利用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];
}
           

2. 利用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;
}
           

備注:在很多情況下,BindingSource對象起到一個過渡的作用,因為SqlDataReader對象直接賦給DataGridView

時,不能正常顯示資料,是以利用BindingSource對象做一個綁定。

3.利用泛型集合向DataGridView中添加資料 

關鍵代碼:(List<>泛型集合)

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<>泛型集合,與List<>泛型集合略有不同)

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;
        }