向DataGridView控件添加数据
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
向DataGridView控件添加数据
在Winform中向DataGridView控件添加数据很常用到,现总结3种填充DataGridView方法:
1.利用SqlDataAdapter对象向DataGridView中添加数据
关键代码:(可以将该代码放到窗体加载事件的方法中)
1.using (SqlDataAdapter da = new SqlDataAdapter("select * f
rom Product", DBService.Conn))
2.{
3. DataSet ds = new DataSet();
4. da.Fill(ds);
5.this.dataGridView1.DataSource = ds.Tables[0];
6.}
2. 利用SqlDataReader填充DataGridView
关键代码:
1. //使用SqlDataReader填充DataGridView
ing (SqlCommand command = new SqlCommand("select * from product", DBService.Conn))
3.{
4. SqlDataReader dr = command.ExecuteReader();
5. BindingSource bs = new BindingSource();
6. bs.DataSource = dr;
7.this.dataGridView1.DataSource = bs;
8.}
备注:在很多情况下,BindingSource对象起到一个过渡的作用,因为SqlDataReader对象直接赋给DataGridView
时,不能正常显示数据,所以利用BindingSource对象做一个绑定。
3.利用泛型集合向DataGridView中添加数据
关键代码:(List<>泛型集合)
1. private void Form1_Load(object sender, EventArgs
e)
2. {
3.//使用List<>泛型集合填充DataGridView
4. List
5. Student hat = new Student("Hathaway", "12", "Male");
6. Student peter = new Student("Peter","14","Male");
7. Student dell = new Student("Dell","16","Male");
8. Student anne = new Student("Anne","19","Female");
9. students.Add(hat);
10. students.Add(peter);
11. students.Add(dell);
12. students.Add(anne);
13.this.dataGridView1.DataSource = students;
14. }
关键代码:(Dictionary<>泛型集合,与List<>泛型集合略有不同)
[csharp]view plaincopy
1. private void Form1_Load(object sender, EventArgs
e)
2. {
3.//使用Dictionary<>泛型集合填充DataGridView
4. Dictionary
5. Student hat = new Student("Hathaway", "12", "Male");
6. Student peter = new Student("Peter","14","Male");
7. Student dell = new Student("Dell","16","Male");
8. Student anne = new Student("Anne","19","Female");
9. students.Add(hat.StuName,hat);
10. students.Add(peter.StuName,peter);
11. students.Add(dell.StuName,dell);
12. students.Add(anne.StuName,anne);
13.//在这里必须创建一个BindIngSource对象,用该对象接收Dictionary<>泛型集合的对象
14. BindingSource bs = new BindingSource();
15.//将泛型集合对象的值赋给BindingSourc对象的数据源
16. bs.DataSource = students.Values;
17.this.dataGridView1.DataSource = bs;
18. }