C#手動操作DataGridView使用各種數(shù)據(jù)源填充表格實例
C#中的表格控件只有一個,那就是datagridview,不像QT中可以用QTableview,QTableWidget。新手拿到datagridview的第一個問題就是數(shù)據(jù)從哪里來?難道從設計器中一個個手動輸入,到時候要變怎辦?所以,我們這里說說DataGridView的手動操作。
一、手動操作DataGridView
這里我們是沒有數(shù)據(jù)源的純view控件的操作,后面第二部分我們再講有數(shù)據(jù)源的操作。
1、初步嘗試
下面的代碼聲明并初始化完成列DataGridViewColumn、行DataGridViewRow 、單元格DataGridViewCell 對象,但這里需要注意的是,DataGridView必須先有列后有行,最后才是單元格cell,初始化完成后你就可以直接將他們加入DataGridView的實例中了,如下代碼dataGridView1就是在設計器的工具箱中直接拖放到窗體中的DataGridView控件。
DataGridViewColumn col = new DataGridViewColumn(); DataGridViewRow row = new DataGridViewRow(); DataGridViewCell cell = new DataGridViewTextBoxCell(); cell.Value = "item"; col.CellTemplate = cell; //設置單元格格式模板 col.HeaderText = "column01"; dataGridView1.Columns.Add(col);
效果:

雖然,只有一行一列一個單元格,但如果我們搞懂了原理,那后面批量加入我們需要的行列和單元格就容易了。
這里了重點強調一下,加入的順序應該是:
1、初始化列
2、初始化行
3、初始化單元格
4、將列column加入DataGridView
5、將行row加入列DataGridView
6、將單元格cell加入行row
注意,一個列必須設定它自己這一列的單元格格式母板,否則就會報錯。如:
cell= new DataGridViewTextBoxCell(); col.CellTemplate = cell;
2、批量加入
批量加入無非就是加入了一些循環(huán),過程和單個單元格的加入幾乎沒有差別,需要注意的是每次加入的行或者列或者單元格都必須是一個新對象,也就是要new一個新的對象,否則就不能成功加入。
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);
}
運行的效果如下:

這里,我們將加入行和加入單元格同時進行的,你也可以加入行和加入列完成后,單獨對單元格進行賦值,代碼如下:
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方法來完成,它有三個重載,所以我們可以用多種方式加入,前面我們就已經使用過了它的最常見的重載,直接在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轉數(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());
運行效果

還有一個重載是add(int ),這個專門從來加入空行,比如加入1000個空行,那就直接在參數(shù)中輸入1000:
dataGridView1.Rows.Add(1000);
二、數(shù)據(jù)來源DataSource
數(shù)據(jù)來源可以是自己從數(shù)據(jù)庫中獲取,也可以自己構建一個DataTable,也可以讀入字符流或者字符列表等。這里分別演示。DataSource它的特點是:任何實現(xiàn)IListSource接口的類都可以作為它的右值。
1、來自列表List
我們將列表中裝入一個對象,當然,這個對象有多少特征,我們就可以顯示在表格中顯示多少列
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();
運行效果:

2、來自自定義DataTable
既然是我們手動自定義的一個表,那么我們就必須給它定義行列和單元格內容。這的Datatable只是提供數(shù)據(jù),與視圖View無關,那么它的責任就是組織好數(shù)據(jù)給視圖來顯示,這在MVC中就屬于model層。
下面的代碼我們初始化了一個DataTable對象后就可以利用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));
關于賦值,使用二維數(shù)組的方式直接給單元格賦值即可:
dt.Rows[i][j]="item" + j.ToString() + i.ToString();
最后,我們給DataGridView實例指定數(shù)據(jù)源DataSource 屬性即可,這里我們指定為我們剛剛手動建立的DataTable。
運行效果:

看起來,和前面我們直接對DataGridView手動操作得到的表格沒有什么兩樣,但實際我們此時已經使用了MVC的概念了,一個負責的是視圖一個負責的是數(shù)據(jù)。
3、動態(tài)建立表格
我們首先定義兩個List分別存放表格的字段類型和值
//定義一個表格的字段類型
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");
//表格字段內容
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);
接下來,我們定義一個函數(shù),專門來建立一個表格
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;
}
}
運行效果:

4、類和BindingList
類的特征屬性直接顯示在表格里可以通過BindingList來實現(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;
運行效果:

5、來自文件字符流
有了上面的基礎后,我們就可以建立一個導入文本文件的表格,并且可以自動識別文本文件中的字段類型。我們首先來看看效果:

導入文本表格要做好文本字段之間的分割Split,這里不詳說了,首先要從讀入的文本流中取出表格的各列的名稱和類型,然后再取出內容,然后分別形成數(shù)組,貼出關鍵代碼:
StreamReader sr = new StreamReader(filepath, Encoding.UTF8);
typetext = sr.ReadLine();
headtext = sr.ReadLine();
string[] typer = typetext.Split(',');
ArrayList content = new ArrayList();
//開始讀文本中的每條記錄的內容
while ((str=sr.ReadLine()) != null)
{
content.Add(str);
Console.WriteLine(str);
}
//定義一個表格的字段類型
List<string> typeDef = new List<string>();
for (int i = 0; i < typer.Length; i++)
{
typeDef.Add("System." + typer[i].ToString());
}
//表格字段內容
ArrayList head = new ArrayList();
string[] header = headtext.Split(',');
for (int i = 0; i < header.Length; i++)
{
head.Add( header[i].ToString());
}
將上述代碼得到的三個列表傳入下面的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);
}
// 加入內容
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、來自數(shù)據(jù)庫
如果有數(shù)據(jù)庫,那是最好不過的啦,直接將查詢所得的表賦值給DataGridView的DataSource即可。這里我們使用sqlite,事先要安裝上sqlite,到Nuget中最快方式獲得。

有了sqlite的環(huán)境,我們可以開始組織數(shù)據(jù)庫讀取了。這里我們調用的句子非常少,其實這是直接通過SQLiteDataAdapter 填充了一個新建的DataTable而已。
//指定數(shù)據(jù)庫地址(我這里就放在debug目錄下) string constr = "Data Source=tbdb.db;"; //設置SQL查詢語句 string sql = "select * from TestTab"; SQLiteDataAdapter mAdapter = new SQLiteDataAdapter(sql, constr); DataTable dt = new DataTable(); mAdapter.Fill(dt); dataGridView1.DataSource = dt;
數(shù)據(jù)庫中的表:

運行效果:

7、用到的student類
上面用到的student類,這里列出來省得大家重新編寫:
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; }
}
其實關于DataGridView的操作還有很多,控件中最復雜的就屬它了,所以如果說你要重新編寫一個自定義控件,它也是最復雜的,這里我們只是講了表格的數(shù)據(jù)填充,后面一篇我們會講到樣式設置和編輯,有時間我們還可以講講自定義DataGridView的編寫。
到此這篇關于C#手動操作DataGridView使用各種數(shù)據(jù)源填充表格實例的文章就介紹到這了,更多相關C# DataGridView數(shù)據(jù)源填充內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
C#?中?List?與?List?多層嵌套不改變原值的實現(xiàn)方法(深度復制)
這篇文章主要介紹了C#?中?List?與?List?多層嵌套不改變原值的實現(xiàn)方法,使用?BinaryFormatter?將原始?List?序列化為字節(jié)流,然后再反序列化得到新的?List,實現(xiàn)了深度復制,需要的朋友可以參考下2024-03-03
Unity輸出帶點擊跳轉功能的Log實現(xiàn)技巧詳解
這篇文章主要為大家介紹了Unity輸出帶點擊跳轉功能的Log實現(xiàn)技巧詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-11-11

