vs mfc数据与控件绑定错了_DataGridView控件用法一:数据绑定

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

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

一、非绑定模式

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

说明
DataGridViewTextBoxColumn与基于文本的值一起使用,在绑定到数字和字符串类型的值时自动生成
DataGridViewCheckBoxColumnbooleancheckState值一起使用,在绑定到这些类型的值时自动生成
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 dict=new Dictionary();

this.dataGridView1.DataSource=dict;

第七种:可以排序

DataView dv=new DataView();

this.dataGridView1.DataSource=dv;

示例程序:

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

1、界面设计如下图:

e16a7ca3f10548afb0fbd2fc9493fdc6.png

2、代码实现如下:

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();        }        ///         /// 非绑定模式        ///         ///         ///         private void btn_NotBinding_Click(object sender, EventArgs e)        {            InitDgvByCustom();        }        ///         /// 通过自定义列的方式初始化DataGridView        ///         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;//不自动产生最后的新行        }        ///         /// 创建DataGridView的TextBox列        ///         /// 要创建列的DataGridView        /// 设置列的对齐方式        /// 列名        /// 显示的标题名        /// 可输入的最大长度        /// 设置列是否只读 true只读 false 读写        /// 设置列是否可见 true 可见 false 不可见        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);        }        ///         /// 创建DataGridView的CheckBox列        ///         /// 要创建列的DataGridView        /// 设置列的对齐方式        /// 列名        /// 显示的标题名        /// 设置列是否只读 true只读 false 读写        /// 设置列是否可见 true 可见 false 不可见        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);        }        ///         /// 绑定模式        ///         ///         ///         private void btn_Binding_Click(object sender, EventArgs e)        {            InitDgvByBinding();        }        ///         /// 通过数据绑定的方式初始化DataGridView        ///         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;        }        ///         /// 都市数据库数据        ///         ///         ///         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;        }        ///         /// 绑定到第一张表        ///         ///         ///         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        }        ///         /// 绑定到第二张表        ///         ///         ///         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        }        ///         /// 绑定到字典        ///         ///         ///         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();        }    }}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值