最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

詳解DataGridView控件的數(shù)據(jù)綁定

 更新時(shí)間:2022年02月26日 10:21:48   作者:.NET開發(fā)菜鳥  
本文詳細(xì)講解了DataGridView控件的數(shù)據(jù)綁定,文中通過示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

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

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

一、非綁定模式

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

說明
DataGridViewTextBoxColumn與基于文本的值一起使用,在綁定到數(shù)字和字符串類型的值時(shí)自動(dòng)生成
DataGridViewCheckBoxColumn與boolean和checkState值一起使用,在綁定到這些類型的值時(shí)自動(dòng)生成
DataGridViewImageColumn用于顯示圖像,在綁定到字節(jié)數(shù)組、Image對(duì)象或Icon對(duì)象自動(dòng)生成
DataGridViewButtonColumn用于在單元格中顯示按鈕,不會(huì)在綁定時(shí)自動(dòng)生成,通常用來做未綁定列
DataGridViewComboBoxColumn用戶在單元格中顯示下拉列表,不會(huì)在綁定時(shí)自動(dòng)生成,通常需要手動(dòng)進(jìn)行數(shù)據(jù)綁定
DataGridViewLinkColumn用于在單元格中顯示超鏈接,不會(huì)在綁定時(shí)自動(dòng)生成,通常需要進(jìn)行手動(dòng)綁定數(shù)據(jù)

二、綁定模式

就是將已經(jīng)存在的數(shù)據(jù)綁定到DataGridView控件上。將數(shù)據(jù)綁定到DataGridView控件上非常簡單和直觀,在大多數(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">可輸入的最大長度</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è)置最大輸入長度
            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();
        }
    }
}

到此這篇關(guān)于DataGridView控件數(shù)據(jù)綁定的文章就介紹到這了。希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • C#中Path類的使用方法

    C#中Path類的使用方法

    這篇文章主要介紹了C#中Path類的使用方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-07-07
  • C# zxing二維碼寫入的實(shí)例代碼

    C# zxing二維碼寫入的實(shí)例代碼

    C# zxing二維碼寫入的實(shí)例代碼,需要的朋友可以參考一下
    2013-03-03
  • C# 遍歷文件夾子目錄下所有圖片及遍歷文件夾下的文件

    C# 遍歷文件夾子目錄下所有圖片及遍歷文件夾下的文件

    在上個(gè)項(xiàng)目開發(fā)中遇到這樣的需求,取指定目錄下面的所有圖片,以表格的型式展示并顯示該圖片的相對(duì)路徑。下面小編給大家分享C# 遍歷文件夾子目錄下所有圖片及遍歷文件夾下的文件,一起看看吧
    2017-01-01
  • 簡單的excel導(dǎo)入導(dǎo)出示例分享

    簡單的excel導(dǎo)入導(dǎo)出示例分享

    這篇文章主要介紹了簡單的excel導(dǎo)入導(dǎo)出示例分享,需要的朋友可以參考下
    2014-03-03
  • 淺析泛型類接口定義

    淺析泛型類接口定義

    在使用泛型定義類的過程中遇到了不少問題,特記錄如下,需要的朋友可以參考下
    2013-07-07
  • C#線程倒計(jì)時(shí)器源碼分享

    C#線程倒計(jì)時(shí)器源碼分享

    這篇文章主要為大家分享了C#線程倒計(jì)時(shí)器源碼,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-01-01
  • C#影院售票系統(tǒng)畢業(yè)設(shè)計(jì)(1)

    C#影院售票系統(tǒng)畢業(yè)設(shè)計(jì)(1)

    這篇文章主要介紹了C#影院售票系統(tǒng)畢業(yè)設(shè)計(jì),獻(xiàn)上了9個(gè)類的設(shè)計(jì),需要的朋友可以參考下
    2015-11-11
  • 詳解C#中的string與String

    詳解C#中的string與String

    本篇文章主要對(duì)jC#中的小寫string與大寫String進(jìn)行詳細(xì)介紹,相信對(duì)大家學(xué)習(xí)會(huì)有很好的幫助,需要的朋友一起來看下吧
    2016-12-12
  • 基于WPF平臺(tái)使用純C#實(shí)現(xiàn)動(dòng)態(tài)處理json字符串

    基于WPF平臺(tái)使用純C#實(shí)現(xiàn)動(dòng)態(tài)處理json字符串

    在當(dāng)今的軟件開發(fā)領(lǐng)域,數(shù)據(jù)的交換與存儲(chǔ)變得愈發(fā)頻繁,JSON作為一種輕量級(jí)的數(shù)據(jù)交換格式,在 WPF平臺(tái)開發(fā)的桌面應(yīng)用里,我們常常需要與各種數(shù)據(jù)源交互,動(dòng)態(tài)處理JSON字符串就成為了一項(xiàng)必備技能,本文將深入探討如何在 WPF 平臺(tái)上,僅使用純C#代碼實(shí)現(xiàn)對(duì)JSON字符串的動(dòng)態(tài)處理
    2025-01-01
  • C#獲取兩個(gè)時(shí)間的時(shí)間差并去除周末(取工作日)的方法

    C#獲取兩個(gè)時(shí)間的時(shí)間差并去除周末(取工作日)的方法

    這篇文章主要介紹了C#獲取兩個(gè)時(shí)間的時(shí)間差并去除周末(取工作日)的方法,可有效的實(shí)現(xiàn)獲取工作日的功能,涉及C#時(shí)間操作的相關(guān)技巧,需要的朋友可以參考下
    2015-05-05

最新評(píng)論

宿州市| 阿坝| 伊金霍洛旗| 南通市| 凤庆县| 武胜县| 霍山县| 湖口县| 阜南县| 象州县| 女性| 长乐市| 黔南| 中卫市| 宜兴市| 纳雍县| 海丰县| 开江县| 关岭| 绥德县| 平泉县| 绥宁县| 钟山县| 侯马市| 福建省| 关岭| 全州县| 黄梅县| 长汀县| 丰原市| 开鲁县| 女性| 四川省| 太谷县| 左贡县| 新乡县| 兖州市| 徐汇区| 泽库县| 伊春市| 海南省|