詳解DataGridView控件的數(shù)據(jù)綁定
使用DataGridView控件,可以顯示和編輯來自多種不同類型的數(shù)據(jù)源的表格數(shù)據(jù)。
將數(shù)據(jù)綁定到DataGridView控件非常簡單和直觀,在大多數(shù)情況下,只需設(shè)置DataSource屬性即可。在綁定到包含多個(gè)列表或表的數(shù)據(jù)源時(shí),只需將DataMember屬性設(shè)置為指定要綁定的列表或表的字符串即可。
一、非綁定模式
所謂的非綁定模式就是DataGridView控件顯示的數(shù)據(jù)不是來自于綁定的數(shù)據(jù)源,而是可以通過代碼手動(dòng)將數(shù)據(jù)填充到DataGridView控件中,這樣就為DataGridView控件增加了很大的靈活性。我們先來了解一下DataGridView控件有多種類型的列,而這些類型都是間接的或直接的繼承了DataGridViewColumns累,下面是我們能夠經(jīng)常用到的幾種類型:
| 類 | 說明 |
| DataGridViewTextBoxColumn | 與基于文本的值一起使用,在綁定到數(shù)字和字符串類型的值時(shí)自動(dòng)生成 |
| DataGridViewCheckBoxColumn | 與boolean和checkState值一起使用,在綁定到這些類型的值時(shí)自動(dòng)生成 |
| DataGridViewImageColumn | 用于顯示圖像,在綁定到字節(jié)數(shù)組、Image對(duì)象或Icon對(duì)象自動(dòng)生成 |
| DataGridViewButtonColumn | 用于在單元格中顯示按鈕,不會(huì)在綁定時(shí)自動(dòng)生成,通常用來做未綁定列 |
| DataGridViewComboBoxColumn | 用戶在單元格中顯示下拉列表,不會(huì)在綁定時(shí)自動(dòng)生成,通常需要手動(dòng)進(jìn)行數(shù)據(jù)綁定 |
| DataGridViewLinkColumn | 用于在單元格中顯示超鏈接,不會(huì)在綁定時(shí)自動(dòng)生成,通常需要進(jìn)行手動(dòng)綁定數(shù)據(jù) |
二、綁定模式
就是將已經(jīng)存在的數(shù)據(jù)綁定到DataGridView控件上。將數(shù)據(jù)綁定到DataGridView控件上非常簡單和直觀,在大多數(shù)情況下,只需設(shè)置DataSource屬性即可。在綁定到包含多個(gè)列表或表的數(shù)據(jù)源時(shí),只需將DataMember屬性設(shè)置為指定要綁定的列表或表的字符串即可。
DataGridView控件支持標(biāo)準(zhǔn)Windows窗體數(shù)據(jù)綁定模型,因此該控件將綁定到下表所述的類的實(shí)例:
- 1、任何實(shí)現(xiàn)IList接口的類,包括一維數(shù)組。
- 2、任何實(shí)現(xiàn)IListSource接口的類,例如DataTable和DataSet。
- 3、任何實(shí)現(xiàn)IBindingList接口的類,例如BindingList(Of T)類。
- 4、任何實(shí)現(xiàn)IBindingListView接口的類,例如BindingSource類。
通常綁定到BindingSource組件,并將BindingSource組件綁定到其他數(shù)據(jù)源或使用業(yè)務(wù)對(duì)象填充該組件。BindingSource組件為首選數(shù)據(jù)源,因?yàn)樵摻M件可以綁定到各種數(shù)據(jù)源,并可以自動(dòng)解決許多數(shù)據(jù)綁定問題。
DataGridView綁定數(shù)據(jù)源的幾種方式:
第一種:
DataSet ds=new DataSet(); this.dataGridView1.DataSource=ds.Tables[0];
第二種:
DataTable dt=new DataTable(); this.dataGridView1.DataSource=dt;
第三種:
DataSet ds=new DataSet(); this.dataGridView1.DataSource=ds.Tables["表名"];
第四種:
DataSet ds=new DataSet(); this.dataGridView1.DataSource=ds; this.dataGridView1.DataMember="表名";//必須要設(shè)置DataMember屬性,指定要綁定到DataSet中的哪張表
第五種:
ArrayList al=new ArrayList(); this.dataGridView1.DataSource=al;
第六種:
Dictionary<string,string> dict=new Dictionary<string,string>(); this.dataGridView1.DataSource=dict;
第七種:可以排序
DataView dv=new DataView(); this.dataGridView1.DataSource=dv;
示例程序:
下面的程序中,演示上面的各種綁定方式
1、界面設(shè)計(jì)如下圖:

2、代碼實(shí)現(xiàn)如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Configuration;
using System.Data.SqlClient;
namespace DataGridViewDataBinding
{
public partial class FrmMain : Form
{
public FrmMain()
{
InitializeComponent();
}
/// <summary>
/// 非綁定模式
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btn_NotBinding_Click(object sender, EventArgs e)
{
InitDgvByCustom();
}
/// <summary>
/// 通過自定義列的方式初始化DataGridView
/// </summary>
private void InitDgvByCustom()
{
//創(chuàng)建列
InitDgvTextBoxColumn(this.dgv_Demo, DataGridViewContentAlignment.MiddleCenter, "UserID", "用戶編號(hào)", 20, true, true);
InitDgvTextBoxColumn(this.dgv_Demo, DataGridViewContentAlignment.MiddleCenter, "UserName", "用戶名", 20, false, true);
InitDgvCheckBoxColumn(this.dgv_Demo, DataGridViewContentAlignment.MiddleCenter, "Sex", "性別", false, true);
//創(chuàng)建行
DataGridViewRow drRow1 = new DataGridViewRow();
drRow1.CreateCells(this.dgv_Demo);
//設(shè)置單元格的值
drRow1.Cells[0].Value = 1;
drRow1.Cells[1].Value = "測試";
drRow1.Cells[2].Value = true;
//將新創(chuàng)建的行添加到DataGridView中
this.dgv_Demo.Rows.Add(drRow1);
//設(shè)置DataGridView的屬性
this.dgv_Demo.AllowUserToAddRows = false;//不自動(dòng)產(chǎn)生最后的新行
}
/// <summary>
/// 創(chuàng)建DataGridView的TextBox列
/// </summary>
/// <param name="dgv">要?jiǎng)?chuàng)建列的DataGridView</param>
/// <param name="_alignmeng">設(shè)置列的對(duì)齊方式</param>
/// <param name="_columnName">列名</param>
/// <param name="_headerText">顯示的標(biāo)題名</param>
/// <param name="_maxInputLength">可輸入的最大長度</param>
/// <param name="_readOnly">設(shè)置列是否只讀 true只讀 false 讀寫</param>
/// <param name="_visible">設(shè)置列是否可見 true 可見 false 不可見</param>
private void InitDgvTextBoxColumn(DataGridView dgv, DataGridViewContentAlignment _alignmeng,
string _columnName, string _headerText, int _maxInputLength, bool _readOnly, bool _visible)
{
//實(shí)例化一個(gè)DataGridViewTextBoxColumn列
DataGridViewTextBoxColumn tbc = new DataGridViewTextBoxColumn();
//設(shè)置對(duì)齊方式
tbc.HeaderCell.Style.Alignment = _alignmeng;
//設(shè)置列名
tbc.Name = _columnName;
//設(shè)置標(biāo)題
tbc.HeaderText = _headerText;
//設(shè)置最大輸入長度
tbc.MaxInputLength = _maxInputLength;
//設(shè)置是否只讀
tbc.ReadOnly = _readOnly;
//設(shè)置是否可見
tbc.Visible = _visible;
//將創(chuàng)建的列添加到DataGridView中
dgv.Columns.Add(tbc);
}
/// <summary>
/// 創(chuàng)建DataGridView的CheckBox列
/// </summary>
/// <param name="dgv">要?jiǎng)?chuàng)建列的DataGridView</param>
/// <param name="_alignmeng">設(shè)置列的對(duì)齊方式</param>
/// <param name="_columnName">列名</param>
/// <param name="_headerText">顯示的標(biāo)題名</param>
/// <param name="_readOnly">設(shè)置列是否只讀 true只讀 false 讀寫</param>
/// <param name="_visible">設(shè)置列是否可見 true 可見 false 不可見</param>
private void InitDgvCheckBoxColumn(DataGridView dgv, DataGridViewContentAlignment _alignmeng,
string _columnName, string _headerText, bool _readOnly, bool _visible)
{
//實(shí)例化一個(gè)DataGridViewTextBoxColumn列
DataGridViewCheckBoxColumn cbc = new DataGridViewCheckBoxColumn();
//設(shè)置對(duì)齊方式
cbc.HeaderCell.Style.Alignment = _alignmeng;
//設(shè)置列名
cbc.Name = _columnName;
//設(shè)置標(biāo)題
cbc.HeaderText = _headerText;
//設(shè)置是否默認(rèn)選中
//cbc.Selected = _selected.Equals("男") ? true : false;
//設(shè)置是否只讀
cbc.ReadOnly = _readOnly;
//設(shè)置是否可見
cbc.Visible = _visible;
//將創(chuàng)建的列添加到DataGridView中
dgv.Columns.Add(cbc);
}
/// <summary>
/// 綁定模式
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btn_Binding_Click(object sender, EventArgs e)
{
InitDgvByBinding();
}
/// <summary>
/// 通過數(shù)據(jù)綁定的方式初始化DataGridView
/// </summary>
private void InitDgvByBinding()
{
#region 綁定單一數(shù)據(jù)源
string strSQL = "select * from users";
//設(shè)置數(shù)據(jù)源
DataTable dtSource = GetDataTable(strSQL);
//直接綁定到表
//this.dgv_Demo.DataSource = dtSource;
//綁定到DataView
DataView dv=dtSource.DefaultView;
//按照Password字段降序排序
dv.Sort = " Password desc";
this.dgv_Demo.DataSource = dv;
#endregion
////不自動(dòng)產(chǎn)生最后的新行
this.dgv_Demo.AllowUserToAddRows = false;
}
/// <summary>
/// 都市數(shù)據(jù)庫數(shù)據(jù)
/// </summary>
/// <param name="strSQL"></param>
/// <returns></returns>
private DataTable GetDataTable(string strSQL)
{
DataTable dtDgv = new DataTable();
//dtDgv.TableName = "";
string strConn = ConfigurationManager.ConnectionStrings["DbConn"].ConnectionString;
SqlConnection conn = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand(strSQL, conn);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
try
{
conn.Open();
adapter.Fill(dtDgv);
}
catch (Exception ex)
{ }
finally
{
conn.Close();
}
return dtDgv;
}
private DataSet GetDataSet()
{
DataSet dsDgv = new DataSet();
//第一張表
string strFirstSQL = "select * from users";
DataTable dtFirst = GetDataTable(strFirstSQL);
//設(shè)置表名
dtFirst.TableName = "UsersTable";
//將表添加到DataSet中
dsDgv.Tables.Add(dtFirst);
//第二張表
string strSecondSQL = "select * from grade";
DataTable dtSecond = GetDataTable(strSecondSQL);
//設(shè)置表名
dtSecond.TableName = "GradeTable";
//將表添加到DataSet中
dsDgv.Tables.Add(dtSecond);
return dsDgv;
}
/// <summary>
/// 綁定到第一張表
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btn_BindingFirst_Click(object sender, EventArgs e)
{
//清空DataGridView
this.dgv_Demo.DataSource = null;
//獲取數(shù)據(jù)集
DataSet dsDataSource = GetDataSet();
#region 方式一
this.dgv_Demo.DataSource = dsDataSource;
//必須設(shè)置DataMember屬性,指定綁定到DataSet的哪張表
this.dgv_Demo.DataMember = "UsersTable";
#endregion
#region 方式二
//this.dgv_Demo.DataSource = dsDataSource.Tables[0];
#endregion
#region 方式三
//this.dgv_Demo.DataSource = dsDataSource.Tables["UsersTable"];
#endregion
}
/// <summary>
/// 綁定到第二張表
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btn_BindingSecond_Click(object sender, EventArgs e)
{
//清空DataGridView
this.dgv_Demo.DataSource = null;
//獲取數(shù)據(jù)集
DataSet dsDataSource = GetDataSet();
#region 方式一
this.dgv_Demo.DataSource = dsDataSource;
//必須設(shè)置DataMember屬性,指定綁定到DataSet的哪張表
this.dgv_Demo.DataMember = "GradeTable";
#endregion
#region 方式二
//this.dgv_Demo.DataSource = dsDataSource.Tables[0];
#endregion
#region 方式三
//this.dgv_Demo.DataSource = dsDataSource.Tables["GradeTable"];
#endregion
}
/// <summary>
/// 綁定到字典
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btn_BindingDict_Click(object sender, EventArgs e)
{
Dictionary<int, string> dictDataSource = new Dictionary<int, string>();
dictDataSource.Add(1, "計(jì)算機(jī)系");
dictDataSource.Add(2, "外語系");
dictDataSource.Add(3, "數(shù)學(xué)系");
dictDataSource.Add(4, "中文系");
DataGridViewTextBoxColumn tbcKey = new DataGridViewTextBoxColumn();
tbcKey.HeaderText = "健";
//設(shè)置要綁定到的字段
tbcKey.DataPropertyName = "Key";
this.dgv_Demo.Columns.Add(tbcKey);
DataGridViewTextBoxColumn tbcValue = new DataGridViewTextBoxColumn();
tbcValue.HeaderText = "值";
//設(shè)置要綁定到的字段
tbcValue.DataPropertyName = "Value";
this.dgv_Demo.Columns.Add(tbcValue);
//設(shè)置數(shù)據(jù)源方式一:字典轉(zhuǎn)換成數(shù)組
//this.dgv_Demo.DataSource = dictDataSource.ToArray();
//設(shè)置數(shù)據(jù)源方式二:字典轉(zhuǎn)換成集合
//this.dgv_Demo.DataSource = dictDataSource.ToList();
//設(shè)置數(shù)據(jù)源方式三
//this.dgv_Demo.DataSource = (from p in dictDataSource
// select new
// {
// Key = p.Key,
// Value = p.Value
// }).ToList();
//設(shè)置數(shù)據(jù)源方式四
this.dgv_Demo.DataSource = (from p in dictDataSource
select new
{
Key = p.Key,
Value = p.Value
}).ToArray();
}
}
}到此這篇關(guān)于DataGridView控件數(shù)據(jù)綁定的文章就介紹到這了。希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
C#?實(shí)例解釋面向?qū)ο缶幊讨械膯我还δ茉瓌t(示例代碼)
本文我介紹了?SOLID?原則中的單一功能原則(single-responsibility?principle),并通過?C#?代碼示例簡明地詮釋了它的含意和實(shí)現(xiàn),對(duì)C#?面向?qū)ο缶幊淘瓌t感興趣的朋友跟隨小編一起看看吧2022-02-02
C#之HttpClient設(shè)置cookies的兩種方式
這篇文章主要介紹了C#之HttpClient設(shè)置cookies的兩種方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-11-11
C#表達(dá)式樹Expression動(dòng)態(tài)創(chuàng)建表達(dá)式
這篇文章介紹了C#表達(dá)式樹Expression動(dòng)態(tài)創(chuàng)建表達(dá)式的方法,對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-12-12
C#實(shí)現(xiàn)運(yùn)行狀態(tài)堆疊柱狀圖
這篇文章主要為大家詳細(xì)介紹了C#實(shí)現(xiàn)運(yùn)行狀態(tài)堆疊柱狀圖,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-02-02
C#操作DataGridView獲取或設(shè)置當(dāng)前單元格的內(nèi)容
這篇文章介紹了C#操作DataGridView獲取或設(shè)置當(dāng)前單元格的內(nèi)容,文中通過示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-02-02
C# 如何在WINForm程序中創(chuàng)建XML文件
這篇文章主要介紹了C# 如何在WINForm程序中創(chuàng)建XML文件,幫助大家更好的理解和學(xué)習(xí)使用c#,感興趣的朋友可以了解下2021-02-02
DevExpress GridView自動(dòng)滾動(dòng)效果
這篇文章主要為大家詳細(xì)介紹了DevExpress GridView自動(dòng)滾動(dòng)效果,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-06-06

