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
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.利用泛型集合向DataGridView中添加数据
private void Form1_Load(object sender, EventArgs e)
{
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;
}
private void Form1_Load(object sender, EventArgs e)
{
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 bs = new BindingSource();
bs.DataSource = students.Values;
this.dataGridView1.DataSource = bs;
}