一、數據填充(反射)
1.封裝
/// <summary>
/// 渲染DataGridView
/// </summary>
/// <param name="dataGridView">被渲染控件</param>
/// <param name="list">數據集</param>
/// <param name="headtext">字段和展示名稱</param>
/// <param name="ButtonList">按鈕名稱,可為空</param>
private void GetDataGridView<T>(DataGridView dataGridView, List<T> list, List<(Expression<Func<T, object>> fields, string name)> headtext, List<string> ButtonList = null) where T : class
{// 使用 LINQ 通過直接提取表達式來獲取字段名稱var propertyNames = headtext.Select(x =>x.fields.Body is MemberExpression memberExpr? memberExpr.Member.Name: ((MemberExpression)((UnaryExpression)x.fields.Body).Operand).Member.Name).ToList();//反射獲取字段列表var field = typeof(T).GetProperties().Where(x=> propertyNames.Contains(x.Name)).OrderBy(x => propertyNames.Contains(x.Name) ? propertyNames.IndexOf(x.Name) : int.MaxValue).ToList();//設置表頭樣式和屬性dataGridView.AllowUserToAddRows = false;//不允許添加、刪除dataGridView.AllowUserToDeleteRows = false;dataGridView.ReadOnly = true;//設置只讀dataGridView.RowHeadersVisible = false;//隱藏最左邊的空白欄dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;//自適應寬度// 設置表頭樣式dataGridView.ColumnHeadersDefaultCellStyle = new DataGridViewCellStyle{Alignment = DataGridViewContentAlignment.MiddleCenter, // 中間對齊BackColor = Color.LightGray, // 表頭背景色ForeColor = Color.Black, // 表頭文字顏色Font = new Font("宋體", 10, FontStyle.Bold), // 表頭字體};//dataGridView.RowTemplate.Height = 80;//設置行高//設置表頭內容(按實體順序依次設置名字)dataGridView.Columns.Clear();foreach (var item in headtext){dataGridView.Columns.Add(new DataGridViewTextBoxColumn //增加文字列{DefaultCellStyle = new DataGridViewCellStyle { Alignment = DataGridViewContentAlignment.MiddleCenter },//劇中對齊HeaderText = item.name,//中文標題MinimumWidth = 6,Name = field[headtext.FindIndex(x => x == item)].Name,//字段的名字 例如ID NameReadOnly = true,SortMode = DataGridViewColumnSortMode.NotSortable,//不要列頭排序,否則無法居中Width = 110});}//設置表頭按鈕if (ButtonList != null){foreach (var item in ButtonList){//增加按鈕(含樣式)dataGridView.Columns.Add(new DataGridViewButtonColumn{DefaultCellStyle = new DataGridViewCellStyle { Alignment = DataGridViewContentAlignment.MiddleCenter },HeaderText = "操作",//中文標題MinimumWidth = 6,Name = item,ReadOnly = true,SortMode = DataGridViewColumnSortMode.NotSortable,Width = 110});}}//dataGridView.Columns[0].Width = 200; // 手動調節寬度,注意需要注釋掉前面的【AutoSizeColumnsMode 自適應寬度】//dataGridView.Columns[1].Width = 200; // 手動調節寬度// dataGridView.Columns[2].Width = 80; // 手動調節寬度// dataGridView.Columns[3].Width = 80; // 手動調節寬度// dataGridView.Columns[4].Width = 80; // 手動調節寬度// dataGridView.Columns[5].Width = 80; // 手動調節寬度// dataGridView.Columns[6].Width = 300; // 手動調節寬度// 清空現有數據dataGridView.Rows.Clear();//添加數據foreach (var item in list){int rowIndex = dataGridView.Rows.Add();foreach (var jtem in field){//添加普通內容數據dataGridView.Rows[rowIndex].Cells[jtem.Name.ToString()].Value = jtem.GetValue(item);//字段dataGridView.Rows[rowIndex].DefaultCellStyle.ForeColor = Color.Black;//if (jtem.Name.ToString().Equals("time"))//對特定的字段處理//{//dataGridView.Rows[rowIndex].Cells[jtem.Name.ToString()].Value = ((DateTime)(jtem.GetValue(item))).ToString("yyyy年MM月dd日");//格式化日期//dataGridView1.Rows[rowIndex].DefaultCellStyle.ForeColor = Color.Red;//文字顏色//dataGridView1.Rows[rowIndex].DefaultCellStyle.BackColor = Color.Yellow;//背景顏色//}//添加按鈕數據if (ButtonList != null){int index = 1;foreach (var j in ButtonList){dataGridView.Rows[rowIndex].Cells[j].Value = j;//按鈕名稱index++;//移除按鈕(兩步)//if (false)//{// dataGridView.Rows[rowIndex].Cells["btn1"] = new DataGridViewTextBoxCell();//重新初始化// dataGridView.Rows[rowIndex].Cells["btn1"].ReadOnly = true; // 設置為只讀//}}}}dataGridView.Rows[rowIndex].Tag = item;//綁定到Tag上方便后續調用}
}
2.使用
private void Form1_Load(object sender, EventArgs e)
{GetDataGridView(dataGridView1,students,new List<(Expression<Func<Student, object>>,string)>{(x => x.StudentId, "學號"),(x => x.StudentName, "姓名"),(x => x.StudentScore, "成績") },new List<string> { "刪除", "修改" });
}
3.效果
二、數據填充(遍歷)
暫未寫
三、點擊按鈕獲取實體?
1.方法
找到你的?dataGridView1?雙擊進入?CellClick
雙擊進去后寫代碼:
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{if (e.ColumnIndex == dataGridView1.Columns["刪除"].Index && e.RowIndex >= 0)//若點擊了【刪除】按鈕{// 獲取當前行對應的實體對象【注意修改此處Student類】,此處能獲取到StudentDorm字段(雖然沒有顯示在界面上,但整個實體也綁定到Tag了)var item = dataGridView1.Rows[e.RowIndex].Tag as Student;MessageBox.Show($"展示內容:學生姓名{item.StudentName},分數{item.StudentScore},學生宿舍{item.StudentDorm}", "點擊了刪除按鈕");}
}
2.效果
?四、點擊單元格獲取實體
?這個和標題三實現起來很相似的
1.方法
找到你的?dataGridView1?雙擊進入?CellClick
雙擊進去后寫代碼:
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{if (e.ColumnIndex == dataGridView1.Columns["StudentName"].Index && e.RowIndex >= 0)//若點擊了【姓名】單元格{// 獲取當前行對應的實體對象【注意修改此處Student類】,此處能獲取到StudentDorm字段(雖然沒有顯示在界面上,但整個實體也綁定到Tag了)var item = dataGridView1.Rows[e.RowIndex].Tag as Student;MessageBox.Show($"展示內容:學生姓名{item.StudentName},分數{item.StudentScore},學生宿舍{item.StudentDorm}", "點擊了【姓名】單元格");}
}
2.效果
五、獲取DatagridView列表
1.封裝
/// <summary>
/// 獲取指定datagridview的列表,并轉化為T實體
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dataGridView"></param>
/// <returns></returns>
private List<T> GetDataGridList<T>(DataGridView dataGridView) where T : class
{List<T> list = new List<T>();foreach (DataGridViewRow row in dataGridView.Rows){var item = row.Tag as T;list.Add(item);}return list;
}
2.使用
//點擊觸發查詢列表
private void button1_Click(object sender, EventArgs e)
{var myList = GetDataGridList<Student>(dataGridView1);
}
3.效果
六、列表的編輯
暫未寫,需要傳出編輯前和編輯后的狀態
七、單條數據的編輯(Key=字段,Value=內容)
暫未寫