在Winform中向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;
        }

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值