怎么在C#中利用DataGridView綁定數(shù)據(jù)源

怎么在C#中利用DataGridView綁定數(shù)據(jù)源?相信很多沒(méi)有經(jīng)驗(yàn)的人對(duì)此束手無(wú)策,為此本文總結(jié)了問(wèn)題出現(xiàn)的原因和解決方法,通過(guò)這篇文章希望你能解決這個(gè)問(wèn)題。

成都創(chuàng)新互聯(lián)公司長(zhǎng)期為超過(guò)千家客戶(hù)提供的網(wǎng)站建設(shè)服務(wù),團(tuán)隊(duì)從業(yè)經(jīng)驗(yàn)10年,關(guān)注不同地域、不同群體,并針對(duì)不同對(duì)象提供差異化的產(chǎn)品和服務(wù);打造開(kāi)放共贏平臺(tái),與合作伙伴共同營(yíng)造健康的互聯(lián)網(wǎng)生態(tài)環(huán)境。為白塔企業(yè)提供專(zhuān)業(yè)的網(wǎng)站設(shè)計(jì)、網(wǎng)站制作,白塔網(wǎng)站改版等技術(shù)服務(wù)。擁有十年豐富建站經(jīng)驗(yàn)和眾多成功案例,為您定制開(kāi)發(fā)。

1. 簡(jiǎn)單的數(shù)據(jù)綁定

例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綁定時(shí),必須同時(shí)指明DateMember 
  this.dataGridView1.DataSource = Ds; 
  this.dataGridView1.DataMember = "T_Class";

  //也可以直接用DataTable來(lái)綁定 
  this.dataGridView1.DataSource = Ds.Tables["T_Class"]; 
}

簡(jiǎn)單的數(shù)據(jù)綁定是將用戶(hù)控件的某一個(gè)屬性綁定至某一個(gè)類(lèi)型實(shí)例上的某一屬性。

采用如下形式進(jìn)行綁定:引用控件.DataBindings.Add("控件屬性", 實(shí)例對(duì)象, "屬性名", true);

例2

從數(shù)據(jù)庫(kù)中把數(shù)據(jù)讀出來(lái)放到一個(gè)數(shù)據(jù)集中,比如List<>、DataTable,DataSet,我一般用List<>,

然后綁定數(shù)據(jù)源:

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

如果你沒(méi)有設(shè)置DataGridView的列,它會(huì)自動(dòng)生成所有列。

2. 復(fù)雜數(shù)據(jù)綁定

復(fù)雜的數(shù)據(jù)綁定是將一個(gè)以列表為基礎(chǔ)的用戶(hù)控件(例如:ComboBox、ListBox、ErrorProvider、DataGridView等控件)綁定至一個(gè)數(shù)據(jù)對(duì)象的列表。

基本上,Windows Forms的復(fù)雜數(shù)據(jù)綁定允許綁定至支持IList接口的數(shù)據(jù)列表。此外,如果想通過(guò)一個(gè)BindingSource組件進(jìn)行綁定,還可以綁定至一個(gè)支持IEnumerable接口的數(shù)據(jù)列表。

對(duì)于復(fù)雜數(shù)據(jù)綁定,常用的數(shù)據(jù)源類(lèi)型有(代碼以DataGridView作為示例控件)。

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接口(包括一維數(shù)組,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接口(包括一維數(shù)組,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類(lèi)) 
  /// </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是一個(gè)結(jié)構(gòu)類(lèi)型DictionaryEntry,同樣的DictionaryEntry并不能直接賦值給Combobox的DataSource,但通過(guò)BindingSource仍然可以間接實(shí)現(xiàn)。 這是因?yàn)椋?/p>

BindingSource可以作為一個(gè)強(qiáng)類(lèi)型的數(shù)據(jù)源。其數(shù)據(jù)源的類(lèi)型通過(guò)以下機(jī)制之一固定。使用 Add 方法可將某項(xiàng)添加到 BindingSource 組件中。

將 DataSource 屬性設(shè)置為一個(gè)列表、單個(gè)對(duì)象或類(lèi)型。(這三者并不一定要實(shí)現(xiàn)IList或IListSource)

這兩種機(jī)制都創(chuàng)建一個(gè)強(qiáng)類(lèi)型列表。BindingSource 支持由其 DataSource 和 DataMember 屬性指示的簡(jiǎn)單數(shù)據(jù)綁定和復(fù)雜數(shù)據(jù)綁定。 

總結(jié):

根據(jù)DataSource綁定的對(duì)象的不同,可以有一下幾種簡(jiǎn)單的綁定:

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

// 設(shè)置了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. 實(shí)例

3.1 手動(dòng)給dataGridView綁定數(shù)據(jù)源的方法

C#中手動(dòng)給dataGridView綁定數(shù)據(jù)源,能夠很自由地進(jìn)行操作,但展示數(shù)據(jù)并沒(méi)有C#自動(dòng)添加數(shù)據(jù)源那么方便。可有時(shí)為了方便操作數(shù)據(jù),我們更愿意手動(dòng)連接數(shù)據(jù)源,代碼如下:

conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Restaurant.mdb");//建立數(shù)據(jù)庫(kù)連接 
cmd = new OleDbCommand("select * from data", conn);//執(zhí)行數(shù)據(jù)連接 
DataSet ds = new DataSet(); 
OleDbDataAdapter da = new OleDbDataAdapter(cmd); 
da.Fill(ds);

this.dataGridView1.DataSource = ds.Tables[0];//數(shù)據(jù)源 
this.dataGridView1.AutoGenerateColumns = false;//不自動(dòng) 
conn.Close();//關(guān)閉數(shù)據(jù)庫(kù)連接

說(shuō)明:解決DataGridView綁定了數(shù)據(jù)源無(wú)法更新保存當(dāng)前行的問(wèn)題

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

3.2 利用泛型集合向DataGridView中添加數(shù)據(jù)

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); 
       //在這里必須創(chuàng)建一個(gè)BindIngSource對(duì)象,用該對(duì)象接收Dictionary<>泛型集合的對(duì)象 
  BindingSource bs = new BindingSource(); 
       //將泛型集合對(duì)象的值賦給BindingSourc對(duì)象的數(shù)據(jù)源 
  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對(duì)象向DataGridView中添加數(shù)據(jù)

using (SqlDataAdapter da = new SqlDataAdapter("select * from Product", DBService.Conn)) 
{ 
   DataSet ds = new DataSet(); 
   da.Fill(ds); 
   this.dataGridView1.DataSource = ds.Tables[0]; 
}

C#是什么

C#是一個(gè)簡(jiǎn)單、通用、面向?qū)ο蟮木幊陶Z(yǔ)言,它由微軟Microsoft開(kāi)發(fā),繼承了C和C++強(qiáng)大功能,并且去掉了一些它們的復(fù)雜特性,C#綜合了VB簡(jiǎn)單的可視化操作和C++的高運(yùn)行效率,以其強(qiáng)大的操作能力、優(yōu)雅的語(yǔ)法風(fēng)格、創(chuàng)新的語(yǔ)言特性和便捷的面向組件編程從而成為.NET開(kāi)發(fā)的首選語(yǔ)言,但它不適用于編寫(xiě)時(shí)間急迫或性能非常高的代碼,因?yàn)镃#缺乏性能極高的應(yīng)用程序所需要的關(guān)鍵功能。

看完上述內(nèi)容,你們掌握怎么在C#中利用DataGridView綁定數(shù)據(jù)源的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝各位的閱讀!

當(dāng)前文章:怎么在C#中利用DataGridView綁定數(shù)據(jù)源
文章位置:http://bm7419.com/article48/jjcpep.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站改版、做網(wǎng)站、響應(yīng)式網(wǎng)站、關(guān)鍵詞優(yōu)化、網(wǎng)站維護(hù)、外貿(mào)建站

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶(hù)投稿、用戶(hù)轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)

成都seo排名網(wǎng)站優(yōu)化