C#DataGridView绑定数据源的几种常见方式
简单数据绑定
示例1:
1 using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["connStr"].ToString())) 2 { 3 4 SqlDataAdapter sda = new SqlDataAdapter("Select * From T_Class Where F_Type='Product' order by F_RootID,F_Orders", conn); 5 DataSet Ds = new DataSet(); 6 sda.Fill(Ds, "T_Class"); 7 8 //使用DataSet绑定时,必须同时指明DateMember 9 this.dataGridView1.DataSource = Ds; 10 this.dataGridView1.DataMember = "T_Class"; 11 12 //也可以直接用DataTable来绑定 13 this.dataGridView1.DataSource = Ds.Tables["T_Class"]; 14 }
简单的数据绑定是将用户控件的某一个属性绑定至某一个类型实例上的某一属性。
采用如下形式进行绑定:引用控件.DataBindings.Add("控件属性", 实例对象, "属性名", true);
示例2:
从数据库中把数据读出来放到一个数据集中,比如List<>、DataTable,DataSet,我一般用List<>,
然后绑定数据源:
1 IList<student> sList=StudentDB.GetAllList(); 2 DataGridView.DataSource=sList;
复杂数据绑定
复杂的数据绑定是将一个以列表为基础的用户控件(例如:ComboBox、ListBox、ErrorProvider、DataGridView等控件)绑定至一个数据对象的列表。
基本上,Windows Forms的复杂数据绑定允许绑定至支持IList接口的数据列表。此外,如果想通过一个BindingSource组件进行绑定,还可以绑定至一个支持IEnumerable接口的数据列表。
对于复杂数据绑定,常用的数据源类型有(代码以DataGridView作为示例控件)。
1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Drawing; 6 using System.Text; 7 using System.Windows.Forms; 8 using System.Collections; 9 10 namespace DataGridViewBindingData 11 { 12 public partial class Form1 : Form 13 { 14 public Form1() 15 { 16 InitializeComponent(); 17 } 18 19 20 private void button1_Click(object sender, EventArgs e) 21 { 22 //this.dataGridView1.DataSource = DataBindingByList1(); 23 //this.dataGridView1.DataSource = DataBindingByList2(); 24 //this.dataGridView1.DataSource = DataBindingByDataTable(); 25 this.dataGridView1.DataSource = DataBindingByBindingSource(); 26 } 27 28 /// <summary> 29 /// IList接口(包括一维数组,ArrayList等) 30 /// </summary> 31 /// <returns></returns> 32 private ArrayList DataBindingByList1() 33 { 34 ArrayList Al = new ArrayList(); 35 Al.Add(new PersonInfo("a","-1")); 36 Al.Add(new PersonInfo("b","-2")); 37 Al.Add(new PersonInfo("c","-3")); 38 return Al; 39 } 40 41 /// <summary> 42 /// IList接口(包括一维数组,ArrayList等) 43 /// </summary> 44 /// <returns></returns> 45 private ArrayList DataBindingByList2() 46 { 47 ArrayList list = new ArrayList(); 48 for (int i = 0; i < 10; i++) 49 { 50 list.Add(new DictionaryEntry(i.ToString(),i.ToString()+"_List")); 51 } 52 return list; 53 } 54 55 56 /// <summary> 57 /// IListSource接口(DataTable、DataSet等) 58 /// </summary> 59 /// <returns></returns> 60 private DataTable DataBindingByDataTable() 61 { 62 DataTable dt = new DataTable(); 63 DataColumn dc1 = new DataColumn("Name"); 64 DataColumn dc2 = new DataColumn("Value"); 65 66 dt.Columns.Add(dc1); 67 dt.Columns.Add(dc2); 68 69 for (int i = 1; i <= 10; i++) 70 { 71 DataRow dr = dt.NewRow(); 72 dr[0] = i; 73 dr[1] = i.ToString() + "_DataTable"; 74 dt.Rows.Add(dr); 75 } 76 77 return dt; 78 } 79 80 81 /// <summary> 82 /// IBindingListView接口(如BindingSource类) 83 /// </summary> 84 /// <returns></returns> 85 private BindingSource DataBindingByBindingSource() 86 { 87 Dictionary<string, string> dic = new Dictionary<string, string>(); 88 for (int i = 0; i < 10; i++) 89 { 90 dic.Add(i.ToString(),i.ToString()+"_Dictionary"); 91 } 92 return new BindingSource(dic,null); } 93 } 94 }
上面代码中BindingSource的Datasource是一个结构类型DictionaryEntry,同样的DictionaryEntry并不能直接赋值给Combobox的DataSource,但通过BindingSource仍然可以间接实现。 这是因为:
BindingSource可以作为一个强类型的数据源。其数据源的类型通过以下机制之一固定。使用 Add 方法可将某项添加到 BindingSource 组件中。
将 DataSource 属性设置为一个列表、单个对象或类型。(这三者并不一定要实现IList或IListSource)
这两种机制都创建一个强类型列表。BindingSource 支持由其 DataSource 和 DataMember 属性指示的简单数据绑定和复杂数据绑定。
根据DataSource绑定的对象不同,可以有以下几种简单的绑定
1 // DataSet 、DataTable 2 3 // 方式1 4 DataSet ds=new DataSet (); 5 this.dataGridView1.DataSource=ds.Table[0]; 6 this.dataGridView1.DataSource = ds.Tables["表名"]; 7 8 // 方式2 9 DataTable dt=new DataTable(); 10 this.dataGridView1.DataSource=dt; 11 12 // DataView 13 DataView dv = new DataView(); 14 this.dataGridView1.DataSource = dv; 15 16 // 设置了DataMember 17 DataSet ds=new DataSet (); 18 this.dataGridView1.DataSource = ds; 19 this.dataGridView1.DataMember = "表名"; 20 21 // ArrayList 22 ArrayList Al = new ArrayList(); 23 this.dataGridView1.DataSource = Al; 24 25 // dic 26 Dictionary<string, string> dic = new Dictionary<string, string>(); 27 this.dataGridView1.DataSource = dic; 28 29 // List<Object> 30 this.dataGridVi.DataSource = new BindingList<Object>(List<Object>);
实例
c#中手动给dataGridView绑定数据源,能够很自由地进行操作,但展示数据并没有C#自动添加数据源那么方便。可有时为了方便操作数据,我们更愿意手动连接数据源,代码如下:
1 conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Restaurant.mdb");//建立数据库连接 2 cmd = new OleDbCommand("select * from data", conn);//执行数据连接 3 DataSet ds = new DataSet(); 4 OleDbDataAdapter da = new OleDbDataAdapter(cmd); 5 da.Fill(ds); 6 this.dataGridView1.DataSource = ds.Tables[0];//数据源 7 this.dataGridView1.AutoGenerateColumns = false;//不自动 8 conn.Close();//关闭数据库连接
说明:
解决DataGridView绑定了数据源无法更新保存当前行的问题
1 this.dataGridView.currentCell=null;//该行的作用是取消datagridview行的编辑状态
2 adapter.Update(userTable);
利用泛型集合向DataGridView中添加数据
List<>泛型集合:
1 private void Form1_Load(object sender, EventArgs e) 2 { 3 //使用List<>泛型集合填充DataGridView 4 List<Student> students = new List<Student>(); 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<>泛型集合
1 private void Form1_Load(object sender, EventArgs e) 2 { 3 //使用Dictionary<>泛型集合填充DataGridView 4 Dictionary<String, Student> students = new Dictionary<String, Student>(); 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 }
Dictionary<>泛型集合
1 private void Form1_Load(object sender, EventArgs e) 2 { 3 //使用Dictionary<>泛型集合填充DataGridView 4 Dictionary<String, Student> students = new Dictionary<String, Student>(); 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 }
利用SqlDataReader填充DataGridView
1 //使用SqlDataReader填充DataGridView 2 using (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 }
利用SqlDataAdapter对象向DataGridView中添加数据
1 //使用SqlDataReader填充DataGridView 2 using (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 }
利用SqlDataAdapter对象向DataGridView中添加数据
1 using (SqlDataAdapter da = new SqlDataAdapter("select * from Product", DBService.Conn)) 2 { 3 DataSet ds = new DataSet(); 4 da.Fill(ds); 5 this.dataGridView1.DataSource = ds.Tables[0]; 6 }
引用文章:C# DataGridView绑定数据源的几种常见方式 - wenglabs - 博客园 (cnblogs.com)