C# DataGridView綁定數據源的幾種常見方式

 

  開始之前,先認識一下WinForm控件數據綁定的兩種形式,簡單數據綁定和複雜數據綁定。 html

1. 簡單的數據綁定

例1數據庫

using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["connStr"].ToString())) 
{  

  SqlDataAdapter sda = new SqlDataAdapter("Select * From T_Class Where F_Type='Product' order by F_RootID,F_Orders", conn); 
  DataSet Ds = new DataSet(); 
  sda.Fill(Ds, "T_Class"); 

  //使用DataSet綁定時,必須同時指明DateMember 
  this.dataGridView1.DataSource = Ds; 
  this.dataGridView1.DataMember = "T_Class"; 

  //也能夠直接用DataTable來綁定 
  this.dataGridView1.DataSource = Ds.Tables["T_Class"]; 
} 

  簡單的數據綁定是將用戶控件的某一個屬性綁定至某一個類型實例上的某一屬性c#

  採用以下形式進行綁定:引用控件.DataBindings.Add("控件屬性", 實例對象, "屬性名", true); 
數組

 

 例2ide

  從數據庫中把數據讀出來放到一個數據集中,好比List<>、DataTable,DataSet,我通常用List<>,
  而後綁定數據源:
ui

IList<student> sList=StudentDB.GetAllList();
DataGridView.DataSource=sList;

 

  若是你沒有設置DataGridView的列,它會自動生成全部列。this

2. 複雜數據綁定 


  複雜的數據綁定是將一個以列表爲基礎的用戶控件(例如:ComboBox、ListBox、ErrorProvider、DataGridView等控件)綁定至一個數據對象的列表。 
  基本上,Windows Forms的複雜數據綁定容許綁定至支持IList接口的數據列表。此外,若是想經過一個BindingSource組件進行綁定,還能夠綁定至一個支持IEnumerable接口的數據列表。 
  對於複雜數據綁定,經常使用的數據源類型有(代碼以DataGridView做爲示例控件)。url

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Text; 
using System.Windows.Forms; 
using System.Collections; 

namespace DataGridViewBindingData 
{ 
public partial class Form1 : Form 
{ 

public Form1() {   InitializeComponent(); } private void button1_Click(object sender, EventArgs e) {   //this.dataGridView1.DataSource = DataBindingByList1();   //this.dataGridView1.DataSource = DataBindingByList2();   //this.dataGridView1.DataSource = DataBindingByDataTable();   this.dataGridView1.DataSource = DataBindingByBindingSource(); } /// <summary> /// IList接口(包括一維數組,ArrayList等) /// </summary> /// <returns></returns> private ArrayList DataBindingByList1() {   ArrayList Al = new ArrayList();   Al.Add(new PersonInfo("a","-1"));   Al.Add(new PersonInfo("b","-2"));   Al.Add(new PersonInfo("c","-3"));   return Al; } /// <summary> /// IList接口(包括一維數組,ArrayList等) /// </summary> /// <returns></returns> private ArrayList DataBindingByList2() {   ArrayList list = new ArrayList();   for (int i = 0; i < 10; i++)   {     list.Add(new DictionaryEntry(i.ToString(),i.ToString()+"_List"));   }   return list; } /// <summary> /// IListSource接口(DataTable、DataSet等) /// </summary> /// <returns></returns> private DataTable DataBindingByDataTable() {   DataTable dt = new DataTable();   DataColumn dc1 = new DataColumn("Name");   DataColumn dc2 = new DataColumn("Value");   dt.Columns.Add(dc1);   dt.Columns.Add(dc2);   for (int i = 1; i <= 10; i++)   {     DataRow dr = dt.NewRow();     dr[0] = i;     dr[1] = i.ToString() + "_DataTable";     dt.Rows.Add(dr);   }   return dt; } /// <summary> /// IBindingListView接口(如BindingSource類) /// </summary> /// <returns></returns> private BindingSource DataBindingByBindingSource() {   Dictionary<string, string> dic = new Dictionary<string, string>();   for (int i = 0; i < 10; i++)   {     dic.Add(i.ToString(),i.ToString()+"_Dictionary");   }   return new BindingSource(dic,null);
}
} }

  

  上面代碼中BindingSource的Datasource是一個結構類型DictionaryEntry,一樣的DictionaryEntry並不能直接賦值給Combobox的DataSource,但經過BindingSource仍然能夠間接實現。 這是由於: 
  BindingSource能夠做爲一個強類型的數據源。其數據源的類型經過如下機制之一固定。使用 Add 方法可將某項添加到 BindingSource 組件中。 
  將 DataSource 屬性設置爲一個列表、單個對象或類型。(這三者並不必定要實現IList或IListSource) 
  這兩種機制都建立一個強類型列表。BindingSource 支持由其 DataSource 和 DataMember 屬性指示的簡單數據綁定和複雜數據綁定。
spa

 

總結:.net

根據DataSource綁定的對象的不一樣,能夠有一下幾種簡單的綁定:

// DataSet 、DataTable // 方式1 DataSet ds=new DataSet (); this.dataGridView1.DataSource=ds.Table[0]; this.dataGridView1.DataSource = ds.Tables["表名"]; // 方式2 DataTable dt=new DataTable(); this.dataGridView1.DataSource=dt; // DataView DataView dv = new DataView(); this.dataGridView1.DataSource = dv; // 設置了DataMember DataSet ds=new DataSet (); this.dataGridView1.DataSource = ds; this.dataGridView1.DataMember = "表名"; // ArrayList ArrayList Al = new ArrayList(); this.dataGridView1.DataSource = Al; // dic Dictionary<string, string> dic = new Dictionary<string, string>(); this.dataGridView1.DataSource = dic; // List<Object> this.dataGridVi.DataSource = new BindingList<Object>(List<Object>);

 

3. 實例

3.1 手動給dataGridView綁定數據源的方法

c#中手動給dataGridView綁定數據源,可以很自由地進行操做,但展現數據並無C#自動添加數據源那麼方便。可有時爲了方便操做數據,咱們更願意手動鏈接數據源,代碼以下:

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();//關閉數據庫鏈接

說明:

解決DataGridView綁定了數據源沒法更新保存當前行的問題

this.dataGridView.currentCell=null;//該行的做用是取消datagridview行的編輯狀態  
adapter.Update(userTable);  

3.2 利用泛型集合向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<>泛型集合

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;  
}

3.3 利用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;  
}

3.4 利用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];  
}

 

參考文章

1. 小白datagridview綁定數據源的幾種常見方式

2. aspnet2005在C#中DataGridView控件怎麼綁定數據庫的數據?

3. officialxiofeC#中DataGridView控件綁定數據源有幾種方式?

4. lllljzc#中手動給dataGridView綁定數據源的方法.

相關文章
相關標籤/搜索