DataGridView控件用法一:數據綁定


使用DataGridView控件,可以顯示和編輯來自多種不同類型的數據源的表格數據。

將數據綁定到DataGridView控件非常簡單和直觀,在大多數情況下,只需設置DataSource屬性即可。在綁定到包含多個列表或表的數據源時,只需將DataMember屬性設置為指定要綁定的列表或表的字符串即可。

一、非綁定模式

所謂的非綁定模式就是DataGridView控件顯示的數據不是來自於綁定的數據源,而是可以通過代碼手動將數據填充到DataGridView控件中,這樣就為DataGridView控件增加了很大的靈活性。我們先來了解一下DataGridView控件有多種類型的列,而這些類型都是間接的或直接的繼承了DataGridViewColumns累,下面是我們能夠經常用到的幾種類型:

說明
DataGridViewTextBoxColumn 與基於文本的值一起使用,在綁定到數字和字符串類型的值時自動生成
DataGridViewCheckBoxColumn booleancheckState值一起使用,在綁定到這些類型的值時自動生成
DataGridViewImageColumn 用於顯示圖像,在綁定到字節數組、Image對象或Icon對象自動生成
DataGridViewButtonColumn 用於在單元格中顯示按鈕,不會在綁定時自動生成,通常用來做未綁定列
DataGridViewComboBoxColumn 用戶在單元格中顯示下拉列表,不會在綁定時自動生成,通常需要手動進行數據綁定
DataGridViewLinkColumn 用於在單元格中顯示超鏈接,不會在綁定時自動生成,通常需要進行手動綁定數據

二、綁定模式

就是將已經存在的數據綁定到DataGridView控件上。將數據綁定到DataGridView控件上非常簡單和直觀,在大多數情況下,只需設置DataSource屬性即可。在綁定到包含多個列表或表的數據源時,只需將DataMember屬性設置為指定要綁定的列表或表的字符串即可。

DataGridView控件支持標准Windows窗體數據綁定模型,因此該控件將綁定到下表所述的類的實例:

1、任何實現IList接口的類,包括一維數組。

2、任何實現IListSource接口的類,例如DataTable和DataSet。

3、任何實現IBindingList接口的類,例如BindingList(Of T)類。

4、任何實現IBindingListView接口的類,例如BindingSource類。

通常綁定到BindingSource組件,並將BindingSource組件綁定到其他數據源或使用業務對象填充該組件。BindingSource組件為首選數據源,因為該組件可以綁定到各種數據源,並可以自動解決許多數據綁定問題。

DataGridView綁定數據源的幾種方式:

第一種:

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、代碼實現如下:

復制代碼
  1 using System;
  2 using System.Collections.Generic;
  3 using System.ComponentModel;
  4 using System.Data;
  5 using System.Drawing;
  6 using System.Linq;
  7 using System.Text;
  8 using System.Threading.Tasks;
  9 using System.Windows.Forms;
 10 using System.Configuration;
 11 using System.Data.SqlClient;
 12 
 13 namespace DataGridViewDataBinding
 14 {
 15     public partial class FrmMain : Form
 16     {
 17         public FrmMain()
 18         {
 19             InitializeComponent();
 20         }
 21 
 22         /// <summary>
 23         /// 非綁定模式
 24         /// </summary>
 25         /// <param name="sender"></param>
 26         /// <param name="e"></param>
 27         private void btn_NotBinding_Click(object sender, EventArgs e)
 28         {
 29             InitDgvByCustom();
 30         }
 31 
 32         /// <summary>
 33         /// 通過自定義列的方式初始化DataGridView
 34         /// </summary>
 35         private void InitDgvByCustom()
 36         {
 37             //創建列
 38             InitDgvTextBoxColumn(this.dgv_Demo, DataGridViewContentAlignment.MiddleCenter, "UserID", "用戶編號", 20, true, true);
 39             InitDgvTextBoxColumn(this.dgv_Demo, DataGridViewContentAlignment.MiddleCenter, "UserName", "用戶名", 20, false, true);
 40             InitDgvCheckBoxColumn(this.dgv_Demo, DataGridViewContentAlignment.MiddleCenter, "Sex", "性別", false, true);
 41 
 42             //創建行
 43             DataGridViewRow drRow1 = new DataGridViewRow();
 44             drRow1.CreateCells(this.dgv_Demo);
 45             //設置單元格的值
 46             drRow1.Cells[0].Value = 1;
 47             drRow1.Cells[1].Value = "測試";
 48             drRow1.Cells[2].Value = true;
 49             //將新創建的行添加到DataGridView中
 50             this.dgv_Demo.Rows.Add(drRow1);
 51 
 52             //設置DataGridView的屬性
 53             this.dgv_Demo.AllowUserToAddRows = false;//不自動產生最后的新行
 54 
 55         }
 56 
 57         /// <summary>
 58         /// 創建DataGridView的TextBox列
 59         /// </summary>
 60         /// <param name="dgv">要創建列的DataGridView</param>
 61         /// <param name="_alignmeng">設置列的對齊方式</param>
 62         /// <param name="_columnName">列名</param>
 63         /// <param name="_headerText">顯示的標題名</param>
 64         /// <param name="_maxInputLength">可輸入的最大長度</param>
 65         /// <param name="_readOnly">設置列是否只讀 true只讀 false 讀寫</param>
 66         /// <param name="_visible">設置列是否可見 true 可見 false 不可見</param>
 67         private void InitDgvTextBoxColumn(DataGridView dgv, DataGridViewContentAlignment _alignmeng,
 68             string _columnName, string _headerText, int _maxInputLength, bool _readOnly, bool _visible)
 69         {
 70             //實例化一個DataGridViewTextBoxColumn列
 71             DataGridViewTextBoxColumn tbc = new DataGridViewTextBoxColumn();
 72             //設置對齊方式
 73             tbc.HeaderCell.Style.Alignment = _alignmeng;
 74             //設置列名
 75             tbc.Name = _columnName;
 76             //設置標題
 77             tbc.HeaderText = _headerText;
 78             //設置最大輸入長度
 79             tbc.MaxInputLength = _maxInputLength;
 80             //設置是否只讀
 81             tbc.ReadOnly = _readOnly;
 82             //設置是否可見
 83             tbc.Visible = _visible;
 84             //將創建的列添加到DataGridView中
 85             dgv.Columns.Add(tbc);
 86         }
 87 
 88         /// <summary>
 89         /// 創建DataGridView的CheckBox列
 90         /// </summary>
 91         /// <param name="dgv">要創建列的DataGridView</param>
 92         /// <param name="_alignmeng">設置列的對齊方式</param>
 93         /// <param name="_columnName">列名</param>
 94         /// <param name="_headerText">顯示的標題名</param>
 95         /// <param name="_readOnly">設置列是否只讀 true只讀 false 讀寫</param>
 96         /// <param name="_visible">設置列是否可見 true 可見 false 不可見</param>
 97         private void InitDgvCheckBoxColumn(DataGridView dgv, DataGridViewContentAlignment _alignmeng,
 98             string _columnName, string _headerText, bool _readOnly, bool _visible)
 99         {
100             //實例化一個DataGridViewTextBoxColumn列
101             DataGridViewCheckBoxColumn cbc = new DataGridViewCheckBoxColumn();
102             //設置對齊方式
103             cbc.HeaderCell.Style.Alignment = _alignmeng;
104             //設置列名
105             cbc.Name = _columnName;
106             //設置標題
107             cbc.HeaderText = _headerText;
108             
109             //設置是否默認選中
110             //cbc.Selected = _selected.Equals("男") ? true : false;
111             //設置是否只讀
112             cbc.ReadOnly = _readOnly;
113             //設置是否可見
114             cbc.Visible = _visible;
115             //將創建的列添加到DataGridView中
116             dgv.Columns.Add(cbc);
117         }
118 
119         /// <summary>
120         /// 綁定模式
121         /// </summary>
122         /// <param name="sender"></param>
123         /// <param name="e"></param>
124         private void btn_Binding_Click(object sender, EventArgs e)
125         {
126             InitDgvByBinding();
127         }
128 
129         /// <summary>
130         /// 通過數據綁定的方式初始化DataGridView
131         /// </summary>
132         private void InitDgvByBinding()
133         {
134             #region 綁定單一數據源
135             string strSQL = "select * from users";
136             //設置數據源
137             DataTable dtSource = GetDataTable(strSQL);
138             //直接綁定到表
139             //this.dgv_Demo.DataSource = dtSource;
140             //綁定到DataView
141             DataView dv=dtSource.DefaultView;
142             //按照Password字段降序排序
143             dv.Sort = " Password desc";
144             this.dgv_Demo.DataSource = dv;
145             #endregion
146 
147             ////不自動產生最后的新行
148             this.dgv_Demo.AllowUserToAddRows = false;
149         }
150 
151         /// <summary>
152         /// 都市數據庫數據
153         /// </summary>
154         /// <param name="strSQL"></param>
155         /// <returns></returns>
156         private DataTable GetDataTable(string strSQL)
157         {
158             DataTable dtDgv = new DataTable();
159             //dtDgv.TableName = "";
160             string strConn = ConfigurationManager.ConnectionStrings["DbConn"].ConnectionString;
161             SqlConnection conn = new SqlConnection(strConn);
162             SqlCommand cmd = new SqlCommand(strSQL, conn);
163             SqlDataAdapter adapter = new SqlDataAdapter(cmd);
164             try
165             {
166                 conn.Open();
167                 adapter.Fill(dtDgv);
168             }
169             catch (Exception ex)
170             { }
171             finally
172             {
173                 conn.Close();
174             }
175             return dtDgv;
176         }
177 
178         private DataSet GetDataSet()
179         {
180             DataSet dsDgv = new DataSet();
181             //第一張表
182             string strFirstSQL = "select * from users";
183             DataTable dtFirst = GetDataTable(strFirstSQL);
184             //設置表名
185             dtFirst.TableName = "UsersTable";
186             //將表添加到DataSet中
187             dsDgv.Tables.Add(dtFirst);
188 
189             //第二張表
190             string strSecondSQL = "select * from grade";
191             DataTable dtSecond = GetDataTable(strSecondSQL);
192             //設置表名
193             dtSecond.TableName = "GradeTable";
194             //將表添加到DataSet中
195             dsDgv.Tables.Add(dtSecond);
196             return dsDgv;
197         }
198 
199         /// <summary>
200         /// 綁定到第一張表
201         /// </summary>
202         /// <param name="sender"></param>
203         /// <param name="e"></param>
204         private void btn_BindingFirst_Click(object sender, EventArgs e)
205         {
206             //清空DataGridView
207             this.dgv_Demo.DataSource = null;
208             //獲取數據集
209             DataSet dsDataSource = GetDataSet();
210 
211 
212             #region 方式一
213             this.dgv_Demo.DataSource = dsDataSource;
214             //必須設置DataMember屬性,指定綁定到DataSet的哪張表
215             this.dgv_Demo.DataMember = "UsersTable"; 
216             #endregion
217 
218             #region 方式二
219             //this.dgv_Demo.DataSource = dsDataSource.Tables[0]; 
220             #endregion
221 
222 
223             #region 方式三
224             //this.dgv_Demo.DataSource = dsDataSource.Tables["UsersTable"]; 
225             #endregion
226         }
227 
228         /// <summary>
229         /// 綁定到第二張表
230         /// </summary>
231         /// <param name="sender"></param>
232         /// <param name="e"></param>
233         private void btn_BindingSecond_Click(object sender, EventArgs e)
234         {
235             //清空DataGridView
236             this.dgv_Demo.DataSource = null;
237             //獲取數據集
238             DataSet dsDataSource = GetDataSet();
239 
240 
241             #region 方式一
242             this.dgv_Demo.DataSource = dsDataSource;
243             //必須設置DataMember屬性,指定綁定到DataSet的哪張表
244             this.dgv_Demo.DataMember = "GradeTable";
245             #endregion
246 
247             #region 方式二
248             //this.dgv_Demo.DataSource = dsDataSource.Tables[0];
249             #endregion
250 
251 
252             #region 方式三
253             //this.dgv_Demo.DataSource = dsDataSource.Tables["GradeTable"];
254             #endregion
255         }
256 
257         /// <summary>
258         /// 綁定到字典
259         /// </summary>
260         /// <param name="sender"></param>
261         /// <param name="e"></param>
262         private void btn_BindingDict_Click(object sender, EventArgs e)
263         {
264             Dictionary<int, string> dictDataSource = new Dictionary<int, string>();
265             dictDataSource.Add(1, "計算機系");
266             dictDataSource.Add(2, "外語系");
267             dictDataSource.Add(3, "數學系");
268             dictDataSource.Add(4, "中文系");
269 
270             DataGridViewTextBoxColumn tbcKey = new DataGridViewTextBoxColumn();
271             tbcKey.HeaderText = "健";
272             //設置要綁定到的字段
273             tbcKey.DataPropertyName = "Key";
274             this.dgv_Demo.Columns.Add(tbcKey);
275 
276             DataGridViewTextBoxColumn tbcValue = new DataGridViewTextBoxColumn();
277             tbcValue.HeaderText = "值";
278             //設置要綁定到的字段
279             tbcValue.DataPropertyName = "Value";
280             this.dgv_Demo.Columns.Add(tbcValue);
281             //設置數據源方式一:字典轉換成數組
282             //this.dgv_Demo.DataSource = dictDataSource.ToArray();
283             //設置數據源方式二:字典轉換成集合
284             //this.dgv_Demo.DataSource = dictDataSource.ToList();
285             //設置數據源方式三
286             //this.dgv_Demo.DataSource = (from p in dictDataSource
287             //                            select new
288             //                            {
289             //                                Key = p.Key,
290             //                                Value = p.Value
291             //                            }).ToList();
292 
293             //設置數據源方式四
294             this.dgv_Demo.DataSource = (from p in dictDataSource
295                                         select new
296                                         {
297                                             Key = p.Key,
298                                             Value = p.Value
299                                         }).ToArray();
300         }
301     }
302 }
復制代碼


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM