码迷,mamicode.com
首页 > Windows程序 > 详细

DataGridView控件用法一:数据绑定

时间:2017-04-09 11:29:32      阅读:371      评论:0      收藏:0      [点我收藏+]

标签:ret   demo   blog   默认   数据源   win   属性   取数   void   

使用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 }

 

DataGridView控件用法一:数据绑定

标签:ret   demo   blog   默认   数据源   win   属性   取数   void   

原文地址:http://www.cnblogs.com/dotnet261010/p/6684041.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!