C#DataGridView绑定数据源的⼏种常见⽅式
 开始以前,先认识⼀下WinForm控件数据绑定的两种形式,简单数据绑定和复杂数据绑定。
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"];
}
  简单的数据绑定是将⽤户控件的某⼀个属性绑定⾄某⼀个类型实例上的某⼀属性。
  采⽤如下形式进⾏绑定:引⽤控件.DataBindings.Add("控件属性", 实例对象, "属性名", true);
例2
  从数据库中把数据读出来放到⼀个数据集中,⽐如List<>、DataTable,DataSet,我⼀般⽤List<>,
  然后绑定数据源:
IList<student> sList=StudentDB.GetAllList();
DataGridView.DataSource=sList;
  如果你没有设置DataGridView的列,它会⾃动⽣成所有列。
2. 复杂数据绑定
  复杂的数据绑定是将⼀个以列表为基础的⽤户控件(例如:ComboBox、ListBox、ErrorProvider、DataGridView等控件)绑定⾄⼀个数据对象的列表。
  基本上,Windows Forms的复杂数据绑定允许绑定⾄⽀持IList接⼝的数据列表。此外,如果想通过⼀个BindingSource组件进⾏绑定,还可以绑定⾄⼀个⽀持IEnumerable接⼝的数据列表。
  对于复杂数据绑定,常⽤的数据源类型有(代码以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接⼝(包括⼀维数组,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 属性指⽰的简单数据绑定和复杂数据绑定。
总结:
根据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)
{datagridview数据源
//使⽤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. ⼩⽩,。
2. ,
3. ,
4. ,

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。