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

2、代碼實現(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", "用戶編號", 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);
//設置單元格的值
drRow1.Cells[0].Value = 1;
drRow1.Cells[1].Value = "測試";
drRow1.Cells[2].Value = true;
//將新創(chuàng)建的行添加到DataGridView中
this.dgv_Demo.Rows.Add(drRow1);
//設置DataGridView的屬性
this.dgv_Demo.AllowUserToAddRows = false;//不自動產(chǎn)生最后的新行
}
/// <summary>
/// 創(chuàng)建DataGridView的TextBox列
/// </summary>
/// <param name="dgv">要創(chuàng)建列的DataGridView</param>
/// <param name="_alignmeng">設置列的對齊方式</param>
/// <param name="_columnName">列名</param>
/// <param name="_headerText">顯示的標題名</param>
/// <param name="_maxInputLength">可輸入的最大長度</param>
/// <param name="_readOnly">設置列是否只讀 true只讀 false 讀寫</param>
/// <param name="_visible">設置列是否可見 true 可見 false 不可見</param>
private void InitDgvTextBoxColumn(DataGridView dgv, DataGridViewContentAlignment _alignmeng,
string _columnName, string _headerText, int _maxInputLength, bool _readOnly, bool _visible)
{
//實例化一個DataGridViewTextBoxColumn列
DataGridViewTextBoxColumn tbc = new DataGridViewTextBoxColumn();
//設置對齊方式
tbc.HeaderCell.Style.Alignment = _alignmeng;
//設置列名
tbc.Name = _columnName;
//設置標題
tbc.HeaderText = _headerText;
//設置最大輸入長度
tbc.MaxInputLength = _maxInputLength;
//設置是否只讀
tbc.ReadOnly = _readOnly;
//設置是否可見
tbc.Visible = _visible;
//將創(chuàng)建的列添加到DataGridView中
dgv.Columns.Add(tbc);
}
/// <summary>
/// 創(chuàng)建DataGridView的CheckBox列
/// </summary>
/// <param name="dgv">要創(chuàng)建列的DataGridView</param>
/// <param name="_alignmeng">設置列的對齊方式</param>
/// <param name="_columnName">列名</param>
/// <param name="_headerText">顯示的標題名</param>
/// <param name="_readOnly">設置列是否只讀 true只讀 false 讀寫</param>
/// <param name="_visible">設置列是否可見 true 可見 false 不可見</param>
private void InitDgvCheckBoxColumn(DataGridView dgv, DataGridViewContentAlignment _alignmeng,
string _columnName, string _headerText, bool _readOnly, bool _visible)
{
//實例化一個DataGridViewTextBoxColumn列
DataGridViewCheckBoxColumn cbc = new DataGridViewCheckBoxColumn();
//設置對齊方式
cbc.HeaderCell.Style.Alignment = _alignmeng;
//設置列名
cbc.Name = _columnName;
//設置標題
cbc.HeaderText = _headerText;
//設置是否默認選中
//cbc.Selected = _selected.Equals("男") ? true : false;
//設置是否只讀
cbc.ReadOnly = _readOnly;
//設置是否可見
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ù)據(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
////不自動產(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);
//設置表名
dtFirst.TableName = "UsersTable";
//將表添加到DataSet中
dsDgv.Tables.Add(dtFirst);
//第二張表
string strSecondSQL = "select * from grade";
DataTable dtSecond = GetDataTable(strSecondSQL);
//設置表名
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;
//必須設置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;
//必須設置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, "計算機系");
dictDataSource.Add(2, "外語系");
dictDataSource.Add(3, "數(shù)學系");
dictDataSource.Add(4, "中文系");
DataGridViewTextBoxColumn tbcKey = new DataGridViewTextBoxColumn();
tbcKey.HeaderText = "健";
//設置要綁定到的字段
tbcKey.DataPropertyName = "Key";
this.dgv_Demo.Columns.Add(tbcKey);
DataGridViewTextBoxColumn tbcValue = new DataGridViewTextBoxColumn();
tbcValue.HeaderText = "值";
//設置要綁定到的字段
tbcValue.DataPropertyName = "Value";
this.dgv_Demo.Columns.Add(tbcValue);
//設置數(shù)據(jù)源方式一:字典轉換成數(shù)組
//this.dgv_Demo.DataSource = dictDataSource.ToArray();
//設置數(shù)據(jù)源方式二:字典轉換成集合
//this.dgv_Demo.DataSource = dictDataSource.ToList();
//設置數(shù)據(jù)源方式三
//this.dgv_Demo.DataSource = (from p in dictDataSource
// select new
// {
// Key = p.Key,
// Value = p.Value
// }).ToList();
//設置數(shù)據(jù)源方式四
this.dgv_Demo.DataSource = (from p in dictDataSource
select new
{
Key = p.Key,
Value = p.Value
}).ToArray();
}
}
}到此這篇關于DataGridView控件數(shù)據(jù)綁定的文章就介紹到這了。希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
基于WPF平臺使用純C#實現(xiàn)動態(tài)處理json字符串
在當今的軟件開發(fā)領域,數(shù)據(jù)的交換與存儲變得愈發(fā)頻繁,JSON作為一種輕量級的數(shù)據(jù)交換格式,在 WPF平臺開發(fā)的桌面應用里,我們常常需要與各種數(shù)據(jù)源交互,動態(tài)處理JSON字符串就成為了一項必備技能,本文將深入探討如何在 WPF 平臺上,僅使用純C#代碼實現(xiàn)對JSON字符串的動態(tài)處理2025-01-01

