DataGridView控件添加数据
在Winform中向DataGridView控件添加数据很常用到,现总结3种填充DataGridView方法:
1. 利用SqlDataAdapter对象向DataGridView中添加数据
关键代码:(可以将该代码放到窗体加载事件的方法中)
<span style="font-size:16px;">using (SqlDataAdapter da = new SqlDataAdapter("select * from Product", DBService.Conn))
{
DataSet ds = new DataSet();
da.Fill(ds);
this.dataGridView1.DataSource = ds.Tables[0];
}</span>
2.利用SqlDataReader填充DataGridView
<span style="font-size:16px;"> //使用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;
}</span>
备注:在很多情况下,BindingSource对象起到一个过渡的作用,因为SqlDataReader对象直接赋给DataGridView
时,不能正常显示数据,所以利用BindingSource对象做一个绑定。
3.利用泛型集合向DataGridView中添加数据
关键代码:(List<>泛型集合)
<span style="font-size:16px;">
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;
}</span>
关键代码:(Dictionary<>泛型集合,与List<>泛型集合略有不同)
<span style="font-size:16px;"> 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;
}</span>
c#中手动给dataGridView绑定数据源,这中方法操作数据的主要好处就是能够很自由,但表现数据没有C#自动添加数据源那么方便,不过我们可以手动给dataGridView添加数据源,如果有兴趣,建议你发5分钟时间研究一下下面的实现方法. 有时为了方便操作数据,我们更愿意手动连接数据源,但表现数据很容易的方法是使用dataGridView,所以我们需要手动将操作的数据绑定到dataGridView,本章就是为实现这样一个方法,代码如下:
conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Restaurant.mdb");//建立数据库连接
cmd = new OleDbCommand("select * from data", conn);//执行数据连接
DataSet ds = new DataSet();
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(ds);
this.dataGridView1.DataSource = ds.Tables[0];//数据源
this.dataGridView1.AutoGenerateColumns = false;//不自动
conn.Close();//关闭数据库连接