欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C#手動(dòng)操作DataGridView使用各種數(shù)據(jù)源填充表格實(shí)例

 更新時(shí)間:2023年02月06日 09:38:37   作者:河西石頭  
本文主要介紹了C#手動(dòng)操作DataGridView使用各種數(shù)據(jù)源填充表格實(shí)例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧

C#中的表格控件只有一個(gè),那就是datagridview,不像QT中可以用QTableview,QTableWidget。新手拿到datagridview的第一個(gè)問題就是數(shù)據(jù)從哪里來(lái)?難道從設(shè)計(jì)器中一個(gè)個(gè)手動(dòng)輸入,到時(shí)候要變?cè)蹀k?所以,我們這里說(shuō)說(shuō)DataGridView的手動(dòng)操作。

一、手動(dòng)操作DataGridView

這里我們是沒有數(shù)據(jù)源的純view控件的操作,后面第二部分我們?cè)僦v有數(shù)據(jù)源的操作。

1、初步嘗試

下面的代碼聲明并初始化完成列DataGridViewColumn、行DataGridViewRow 、單元格DataGridViewCell 對(duì)象,但這里需要注意的是,DataGridView必須先有列后有行,最后才是單元格cell,初始化完成后你就可以直接將他們加入DataGridView的實(shí)例中了,如下代碼dataGridView1就是在設(shè)計(jì)器的工具箱中直接拖放到窗體中的DataGridView控件。

  DataGridViewColumn col = new DataGridViewColumn();
  DataGridViewRow row = new DataGridViewRow();
  DataGridViewCell cell = new DataGridViewTextBoxCell();
  cell.Value = "item";
  col.CellTemplate = cell; //設(shè)置單元格格式模板
  col.HeaderText = "column01";
  dataGridView1.Columns.Add(col);

效果:

在這里插入圖片描述

雖然,只有一行一列一個(gè)單元格,但如果我們搞懂了原理,那后面批量加入我們需要的行列和單元格就容易了。
這里了重點(diǎn)強(qiáng)調(diào)一下,加入的順序應(yīng)該是:
1、初始化列
2、初始化行
3、初始化單元格
4、將列column加入DataGridView
5、將行row加入列DataGridView
6、將單元格cell加入行row

注意,一個(gè)列必須設(shè)定它自己這一列的單元格格式母板,否則就會(huì)報(bào)錯(cuò)。如:

cell= new DataGridViewTextBoxCell();
 col.CellTemplate = cell;

2、批量加入

批量加入無(wú)非就是加入了一些循環(huán),過程和單個(gè)單元格的加入幾乎沒有差別,需要注意的是每次加入的行或者列或者單元格都必須是一個(gè)新對(duì)象,也就是要new一個(gè)新的對(duì)象,否則就不能成功加入。

 DataGridViewColumn col;
 DataGridViewRow row;
 DataGridViewCell cell= new DataGridViewTextBoxCell();
         
 for (int i = 0; i < 6; i++)
 {
     col = new DataGridViewColumn();
     col.HeaderText = "col" + i.ToString();       
     col.CellTemplate = cell;
     dataGridView1.Columns.Add(col);
     }
            
 for (int i = 0; i <20; i++)
  {
      row = new DataGridViewRow(); 
      for (int j = 0; j < 6; j++)
      {
         cell = new DataGridViewTextBoxCell();
         cell.Value = "item" + i.ToString() + j.ToString();
         row.Cells.Add(cell);
      }
      dataGridView1.Rows.Add(row);
   
   }

運(yùn)行的效果如下:

在這里插入圖片描述

這里,我們將加入行和加入單元格同時(shí)進(jìn)行的,你也可以加入行和加入列完成后,單獨(dú)對(duì)單元格進(jìn)行賦值,代碼如下:

 for (int i = 0; i < 20; i++)
  {
      row = new DataGridViewRow();
      //for (int j = 0; j < 6; j++)
      //{
      //    cell = new DataGridViewTextBoxCell();
      //    cell.Value = "item" + i.ToString() + j.ToString();
      //    row.Cells.Add(cell);
      //}
      dataGridView1.Rows.Add(row);
  }

  for (int i = 0; i < 6; i++)
      for (int j = 0; j < 20; j++)
          dataGridView1.Rows[j].Cells[i].Value = "item" + j.ToString() + i.ToString();

3、帶數(shù)據(jù)的行的加入rows.Add

行的加入我們利用add方法來(lái)完成,它有三個(gè)重載,所以我們可以用多種方式加入,前面我們就已經(jīng)使用過了它的最常見的重載,直接在add的參數(shù)中加入row
如:

dataGridView1.Rows.Add(row);

這里我們使用數(shù)組加入也很方便:

    //添加行
     string[] row0 = { "Jack", "1880", "2022-12-5","12.5","true" };
     string[] row1 = { "Smith", "2208", "2022-02-15", "538", "true" };
     dataGridView1.Rows.Add(row0);
     dataGridView1.Rows.Add(row1);
     dataGridView1.Rows.Add(new string[] { "Tome", "1208", "2012-2-15", "1.2", "true" });
     //list轉(zhuǎn)數(shù)組后加入
     List<string> values = new List<string>();
     values.Add("Jone");
     values.Add("1222");      
     values.Add("2022-05-12");
     values.Add("23.2");
     values.Add("false");
     dataGridView1.Rows.Add(values.ToArray());

運(yùn)行效果

在這里插入圖片描述

還有一個(gè)重載是add(int ),這個(gè)專門從來(lái)加入空行,比如加入1000個(gè)空行,那就直接在參數(shù)中輸入1000:

dataGridView1.Rows.Add(1000);

二、數(shù)據(jù)來(lái)源DataSource

數(shù)據(jù)來(lái)源可以是自己從數(shù)據(jù)庫(kù)中獲取,也可以自己構(gòu)建一個(gè)DataTable,也可以讀入字符流或者字符列表等。這里分別演示。DataSource它的特點(diǎn)是:任何實(shí)現(xiàn)IListSource接口的類都可以作為它的右值。

1、來(lái)自列表List

我們將列表中裝入一個(gè)對(duì)象,當(dāng)然,這個(gè)對(duì)象有多少特征,我們就可以顯示在表格中顯示多少列

 List<Student> students = new List<Student>()
 {
      new Student() {Name="John", Gender=true, Birthday=new DateTime(2012, 12, 4),Age= 20, Hight=15},
      new Student() {Name="Jack",  Gender=true, Birthday=new DateTime(2022, 10, 12), Age=10, Hight=125}
  };
  dataGridView1.DataSource = students.Select(x => new { x.Name, x.Gender, x.Birthday, x.Age, x.Hight }).ToList();

運(yùn)行效果:

在這里插入圖片描述

2、來(lái)自自定義DataTable

既然是我們手動(dòng)自定義的一個(gè)表,那么我們就必須給它定義行列和單元格內(nèi)容。這的Datatable只是提供數(shù)據(jù),與視圖View無(wú)關(guān),那么它的責(zé)任就是組織好數(shù)據(jù)給視圖來(lái)顯示,這在MVC中就屬于model層。
下面的代碼我們初始化了一個(gè)DataTable對(duì)象后就可以利用columns.add增加列了,增加完列我們用DataTable的newRow()方法直接增加行,沒有它法。

     DataTable dt = new DataTable();
     dt.Columns.Add("col1", typeof(System.String));
     dt.Columns.Add("col2", typeof(System.String));
     dt.Columns.Add("col3", typeof(System.String));
     dt.Columns.Add("col4", typeof(System.String));
     dt.Columns.Add("col5", typeof(System.String));
     dt.Columns.Add("col6", typeof(System.String));

     for(int i = 0; i < 10; i++)
     {
         dt.Rows.Add(dt.NewRow());
         for(int j = 0; j < 6; j++)
             dt.Rows[i][j]="item" + j.ToString() + i.ToString();
     }
	dataGridView1.DataSource =dt;

我們上面所有的行,我們使用的格式都是String的,便于統(tǒng)一用循環(huán)添加,我們我們想要添加其他的格式的數(shù)據(jù)可以這樣添加:

 DataTable dt = new DataTable();

 dt.Columns.Add("col1", typeof(System.Int32));
 dt.Columns.Add("col2", typeof(System.String));
 dt.Columns.Add("col3", typeof(System.DateTime));
 dt.Columns.Add("col4", typeof(System.Boolean));
 dt.Columns.Add("col5", typeof(System.Int16));
 dt.Columns.Add("col6", typeof(System.Decimal));

關(guān)于賦值,使用二維數(shù)組的方式直接給單元格賦值即可:

dt.Rows[i][j]="item" + j.ToString() + i.ToString();

最后,我們給DataGridView實(shí)例指定數(shù)據(jù)源DataSource 屬性即可,這里我們指定為我們剛剛手動(dòng)建立的DataTable。

運(yùn)行效果:

在這里插入圖片描述

看起來(lái),和前面我們直接對(duì)DataGridView手動(dòng)操作得到的表格沒有什么兩樣,但實(shí)際我們此時(shí)已經(jīng)使用了MVC的概念了,一個(gè)負(fù)責(zé)的是視圖一個(gè)負(fù)責(zé)的是數(shù)據(jù)。

3、動(dòng)態(tài)建立表格

我們首先定義兩個(gè)List分別存放表格的字段類型和值

            //定義一個(gè)表格的字段類型
            List<string> typeDef = new List<string>();
            typeDef.Add("System.Int32");
            typeDef.Add("System.String");
            typeDef.Add("System.DateTime");
            typeDef.Add("System.Decimal");
            typeDef.Add("System.Boolean");

            //表格字段內(nèi)容
            List<string> values = new List<string>();
            values.Add("1222");
            values.Add("Jone");
            values.Add("2022-05-12");
            values.Add("23.2");
            values.Add("false");
            dataGridView1.DataSource = initialDataTable(typeDef,values);

接下來(lái),我們定義一個(gè)函數(shù),專門來(lái)建立一個(gè)表格

  DataTable initialDataTable(List<String> strlist, List<String> vluelist)
        {

            DataTable dt = new DataTable();

            DataColumn col = new DataColumn();
            for (int i = 0; i < strlist.Count; i++)
            {
                col = new DataColumn();
                col.DataType = System.Type.GetType(strlist[i]);
                dt.Columns.Add(col);
            }

            for (int i = 0; i < 10; i++)
            {
                dt.Rows.Add(dt.NewRow());
                for (int j = 0; j < strlist.Count; j++)
                    dt.Rows[i][j] = vluelist[j];
            }

            return dt;

        }
    }

運(yùn)行效果:

在這里插入圖片描述

4、類和BindingList

類的特征屬性直接顯示在表格里可以通過BindingList來(lái)實(shí)現(xiàn)

BindingList<Student> list2 = new BindingList<Student>();
list2.Add(new Student("John", true, new DateTime(2012, 12, 4), 20, 15));
list2.Add(new Student("Jack", true, new DateTime(2022, 10, 12), 10, 125));
list2.Add(new Student("Tomy", true, new DateTime(1992, 3, 5), 30, 5));
dataGridView1.DataSource= list2;

運(yùn)行效果:

在這里插入圖片描述

5、來(lái)自文件字符流

有了上面的基礎(chǔ)后,我們就可以建立一個(gè)導(dǎo)入文本文件的表格,并且可以自動(dòng)識(shí)別文本文件中的字段類型。我們首先來(lái)看看效果:

在這里插入圖片描述

導(dǎo)入文本表格要做好文本字段之間的分割Split,這里不詳說(shuō)了,首先要從讀入的文本流中取出表格的各列的名稱和類型,然后再取出內(nèi)容,然后分別形成數(shù)組,貼出關(guān)鍵代碼:

 			StreamReader sr = new StreamReader(filepath, Encoding.UTF8);
            typetext = sr.ReadLine();
            headtext = sr.ReadLine();
            string[] typer = typetext.Split(',');
            ArrayList content = new ArrayList();
            //開始讀文本中的每條記錄的內(nèi)容
            while ((str=sr.ReadLine()) != null)
            {
                content.Add(str);
                Console.WriteLine(str); 
            }
            //定義一個(gè)表格的字段類型
            List<string> typeDef = new List<string>();
            for (int i = 0; i < typer.Length; i++)
            {
                typeDef.Add("System." + typer[i].ToString());
             }

            //表格字段內(nèi)容
            ArrayList head = new ArrayList();
            string[] header = headtext.Split(',');
            for (int i = 0; i < header.Length; i++)
            {
                head.Add( header[i].ToString());
            }

將上述代碼得到的三個(gè)列表傳入下面的DataTable處理函數(shù)中即可得到DataGridView的DataSource需要的DataTable

       DataTable initialDataTable(List<String> typelist, ArrayList headerlist,ArrayList contentarry)
        {

            DataTable dt = new DataTable();
            DataColumn col = new DataColumn();
            for (int i = 0; i < headerlist.Count; i++)
            {
                col = new DataColumn();
                col.ColumnName = headerlist[i].ToString();
                col.DataType = System.Type.GetType(typelist[i]);
                dt.Columns.Add(col);
            }
            // 加入內(nèi)容
            for (int i = 0; i < contentarry.Count; i++)
            {
                dt.Rows.Add(contentarry[i].ToString().Split(','));               
            }
            return dt;
        }

可以參考的文本:

String,Boolean,Int32,DateTime,Int32,Int32
Name,Gender,ID,Birthday,Score1,Score2
John, true,1908, 2012-12-4, 20, 16
Jack, false2015, 2022-10-12, 10, 125
Tomy, true, 2047,1992-3-5, 30, 15,
Mophy, true, 1147,2014-6-3, 40, 24
Tollor, false,2347,2102-2-15, 50, 55

6、來(lái)自數(shù)據(jù)庫(kù)

如果有數(shù)據(jù)庫(kù),那是最好不過的啦,直接將查詢所得的表賦值給DataGridView的DataSource即可。這里我們使用sqlite,事先要安裝上sqlite,到Nuget中最快方式獲得。

在這里插入圖片描述

有了sqlite的環(huán)境,我們可以開始組織數(shù)據(jù)庫(kù)讀取了。這里我們調(diào)用的句子非常少,其實(shí)這是直接通過SQLiteDataAdapter 填充了一個(gè)新建的DataTable而已。

  //指定數(shù)據(jù)庫(kù)地址(我這里就放在debug目錄下)
  string constr = "Data Source=tbdb.db;";
   //設(shè)置SQL查詢語(yǔ)句
  string sql = "select * from TestTab";
  SQLiteDataAdapter mAdapter = new SQLiteDataAdapter(sql, constr);
  DataTable dt = new DataTable();
  mAdapter.Fill(dt);
  dataGridView1.DataSource = dt;           

數(shù)據(jù)庫(kù)中的表:

在這里插入圖片描述

運(yùn)行效果:

在這里插入圖片描述

7、用到的student類

上面用到的student類,這里列出來(lái)省得大家重新編寫:

class Student
{
    string _name = "";
    bool _gender =false;
    DateTime _birthday;
    int _age;
    decimal _hight;
    public string School;

    public Student() {

        School = "";
    }

    public  Student(string name, bool gender, DateTime birthday, int age, decimal hight)
    {
        Name = name;
        Gender = gender;
        Birthday = birthday;
        Age = age;
        Hight = hight;
        School = "";     
    }

    public string Name{get { return _name; }set { _name = value; }}
    public bool Gender{get { return _gender; } set { _gender = value; }}
    public DateTime Birthday{ get { return _birthday; } set { _birthday = value; } }
    public int Age { get { return _age; } set { _age = value; } }
    public decimal Hight { get { return _hight; } set { _hight = value; } }
    public List<int> Scores { get; set; }
}

其實(shí)關(guān)于DataGridView的操作還有很多,控件中最復(fù)雜的就屬它了,所以如果說(shuō)你要重新編寫一個(gè)自定義控件,它也是最復(fù)雜的,這里我們只是講了表格的數(shù)據(jù)填充,后面一篇我們會(huì)講到樣式設(shè)置和編輯,有時(shí)間我們還可以講講自定義DataGridView的編寫。

到此這篇關(guān)于C#手動(dòng)操作DataGridView使用各種數(shù)據(jù)源填充表格實(shí)例的文章就介紹到這了,更多相關(guān)C# DataGridView數(shù)據(jù)源填充內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論