服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C# - 详解DataGridView控件的数据绑定

详解DataGridView控件的数据绑定

2023-02-15 15:55.NET开发菜鸟 C#

本文详细讲解了DataGridView控件的数据绑定,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

使用DataGridView控件,可以显示和编辑来自多种不同类型的数据源的表格数据。

将数据绑定到DataGridView控件非常简单和直观,在大多数情况下,只需设置DataSource属性即可。在绑定到包含多个列表或表的数据源时,只需将DataMember属性设置为指定要绑定的列表或表的字符串即可。

一、非绑定模式

所谓的非绑定模式就是DataGridView控件显示的数据不是来自于绑定的数据源,而是可以通过代码手动将数据填充到DataGridView控件中,这样就为DataGridView控件增加了很大的灵活性。我们先来了解一下DataGridView控件有多种类型的列,而这些类型都是间接的或直接的继承了DataGridViewColumns累,下面是我们能够经常用到的几种类型:

说明
DataGridViewTextBoxColumn 与基于文本的值一起使用,在绑定到数字和字符串类型的值时自动生成
DataGridViewCheckBoxColumn 与boolean和checkState值一起使用,在绑定到这些类型的值时自动生成
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绑定数据源的几种方式:

第一种:

?
1
2
DataSet ds=new DataSet();
this.dataGridView1.DataSource=ds.Tables[0];

第二种:

?
1
2
DataTable dt=new DataTable();
this.dataGridView1.DataSource=dt;

第三种:

?
1
2
DataSet ds=new DataSet();
this.dataGridView1.DataSource=ds.Tables["表名"];

第四种:

?
1
2
3
DataSet ds=new DataSet();
this.dataGridView1.DataSource=ds;
this.dataGridView1.DataMember="表名";//必须要设置DataMember属性,指定要绑定到DataSet中的哪张表

第五种:

?
1
2
ArrayList al=new ArrayList();
this.dataGridView1.DataSource=al;

第六种:

?
1
2
Dictionary<string,string> dict=new Dictionary<string,string>();
this.dataGridView1.DataSource=dict;

第七种:可以排序

?
1
2
DataView dv=new DataView();
this.dataGridView1.DataSource=dv;

示例程序:

下面的程序中,演示上面的各种绑定方式

1、界面设计如下图:

 

详解DataGridView控件的数据绑定

2、代码实现如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
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()
        {
            //创建列
            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);
 
            //创建行
            DataGridViewRow drRow1 = new DataGridViewRow();
            drRow1.CreateCells(this.dgv_Demo);
            //设置单元格的值
            drRow1.Cells[0].Value = 1;
            drRow1.Cells[1].Value = "测试";
            drRow1.Cells[2].Value = true;
            //将新创建的行添加到DataGridView中
            this.dgv_Demo.Rows.Add(drRow1);
 
            //设置DataGridView的属性
            this.dgv_Demo.AllowUserToAddRows = false;//不自动产生最后的新行
 
        }
 
        /// <summary>
        /// 创建DataGridView的TextBox列
        /// </summary>
        /// <param name="dgv">要创建列的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;
            //将创建的列添加到DataGridView中
            dgv.Columns.Add(tbc);
        }
 
        /// <summary>
        /// 创建DataGridView的CheckBox列
        /// </summary>
        /// <param name="dgv">要创建列的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;
            //将创建的列添加到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>
        /// 通过数据绑定的方式初始化DataGridView
        /// </summary>
        private void InitDgvByBinding()
        {
            #region 绑定单一数据源
            string strSQL = "select * from users";
            //设置数据源
            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
 
            ////不自动产生最后的新行
            this.dgv_Demo.AllowUserToAddRows = false;
        }
 
        /// <summary>
        /// 都市数据库数据
        /// </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;
            //获取数据集
            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;
            //获取数据集
            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, "数学系");
            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);
            //设置数据源方式一:字典转换成数组
            //this.dgv_Demo.DataSource = dictDataSource.ToArray();
            //设置数据源方式二:字典转换成集合
            //this.dgv_Demo.DataSource = dictDataSource.ToList();
            //设置数据源方式三
            //this.dgv_Demo.DataSource = (from p in dictDataSource
            //                            select new
            //                            {
            //                                Key = p.Key,
            //                                Value = p.Value
            //                            }).ToList();
 
            //设置数据源方式四
            this.dgv_Demo.DataSource = (from p in dictDataSource
                                        select new
                                        {
                                            Key = p.Key,
                                            Value = p.Value
                                        }).ToArray();
        }
    }
}

到此这篇关于DataGridView控件数据绑定的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://www.cnblogs.com/dotnet261010/p/6684041.html

延伸 · 阅读

精彩推荐
  • C#c# SqlDataAdapter中的Fill是怎么实现的

    c# SqlDataAdapter中的Fill是怎么实现的

    这篇文章主要介绍了c# SqlDataAdapter中的Fill是怎么实现的,文中讲解非常细致,代码帮助大家更好的理解和学习,感兴趣的朋友可以了解下...

    一线码农4452022-09-28
  • C#C#实现根据实体类自动创建数据库表

    C#实现根据实体类自动创建数据库表

    本文主要介绍了C#通过自定义特性实现根据实体类自动创建数据库表的方法。具有很好的参考价值,需要的朋友一起来看下吧...

    天碼行空5232021-12-15
  • C#vscode编写latex的方法

    vscode编写latex的方法

    这篇文章主要介绍了vscode编写latex的方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...

    Nightmare0043372022-11-25
  • C#使用Linq注意事项避免报错的方法

    使用Linq注意事项避免报错的方法

    这篇文章主要介绍了使用Linq注意事项避免报错的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们...

    森大科技9012022-08-16
  • C#C# 添加PDF页眉/页脚的示例代码

    C# 添加PDF页眉/页脚的示例代码

    这篇文章主要介绍了C# 添加PDF页眉/页脚的示例代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧...

    Miaonly9772022-02-28
  • C#C#开启线程的四种示例

    C#开启线程的四种示例

    这篇文章主要介绍了C#开启线程的四种方法,帮助大家更好的理解和使用c#,感兴趣的朋友可以了解下...

    zls3656622022-10-11
  • C#Unity使用LineRender实现签名效果

    Unity使用LineRender实现签名效果

    这篇文章主要为大家详细介绍了Unity使用LineRender实现签名效果,制作签名功能,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可...

    吸血鬼112410482022-12-06
  • C#c# 判断是否为空然后赋值的4种实现方法

    c# 判断是否为空然后赋值的4种实现方法

    下面小编就为大家分享一篇c# 判断是否为空然后赋值的4种实现方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...

    杨明波(Leo Yang)7172022-02-16