用DataGridView控件,,可以顯示和編輯來自多種不同類型的數(shù)據(jù)源的表格數(shù)據(jù),。 將數(shù)據(jù)綁定到DataGridView控件非常簡(jiǎn)單和直觀,在大多數(shù)情況下,,只需設(shè)置DataSource屬性即可,。在綁定到包含多個(gè)列表或表的數(shù)據(jù)源時(shí),只需將DataMember屬性設(shè)置為指定要綁定的列表或表的字符串即可,。 一,、非綁定模式 所謂的非綁定模式就是DataGridView控件顯示的數(shù)據(jù)不是來自于綁定的數(shù)據(jù)源,而是可以通過代碼手動(dòng)將數(shù)據(jù)填充到DataGridView控件中,,這樣就為DataGridView控件增加了很大的靈活性,。我們先來了解一下DataGridView控件有多種類型的列,而這些類型都是間接的或直接的繼承了DataGridViewColumns累,,下面是我們能夠經(jīng)常用到的幾種類型:
二,、綁定模式 就是將已經(jīng)存在的數(shù)據(jù)綁定到DataGridView控件上。將數(shù)據(jù)綁定到DataGridView控件上非常簡(jiǎn)單和直觀,,在大多數(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 = "測(cè)試"; 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">可輸入的最大長(zhǎng)度</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è)置最大輸入長(zhǎng)度 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(); |
|