C#高級:Winform桌面開發中DataGridView的詳解(新)

一、數據填充(反射)

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=內容)

暫未寫

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/bicheng/86748.shtml
繁體地址,請注明出處:http://hk.pswp.cn/bicheng/86748.shtml
英文地址,請注明出處:http://en.pswp.cn/bicheng/86748.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

人臉活體識別2:Pytorch實現人臉眨眼 張嘴 點頭 搖頭識別(含訓練代碼和數據集)

人臉活體識別2&#xff1a;Pytorch實現人臉眨眼 張嘴 點頭 搖頭識別(含訓練代碼和數據集) 目錄 人臉活體識別2&#xff1a;Pytorch實現人臉眨眼 張嘴 點頭 搖頭識別(含訓練代碼和數據集) 1. 前言 2.人臉活體識別方法 &#xff08;1&#xff09;基于人臉動作的檢測?? &a…

Webpack 自定義插件開發指南:構建流程詳解與實戰開發全攻略

一. webpack打包流程 開發 Webpack 插件的第一步&#xff0c;就是明確&#xff1a;我的插件要接入 Webpack 構建流程的哪個階段&#xff0c;解決什么問題。 了解流程之前首先要了解插件的兩個核心概念&#xff1a;compiler&#xff0c;compilation 1. compiler&#xff1a;全局…

本地部署Dify+Ragflow及使用(一)

概念說明 RAGflow&#xff1a; 吃透知識&#xff1a;將企業文檔&#xff08;如技術白皮書&#xff09;解析為結構化知識片段。精準檢索&#xff1a;當用戶提問時&#xff0c;從知識庫中召回最相關內容。 模型供應商&#xff1a; 提供大腦&#xff1a;為 Dify 提供生成答案的模…

2025.06.24【R語言】|clusterProfiler安裝與常見報錯FAQ全解

文章目錄 一、clusterProfiler安裝方法1. Bioconductor官方推薦2. Conda安裝&#xff08;個人推薦 適合服務器/依賴復雜環境&#xff09;3. 檢查安裝 二、常見依賴包安裝三、常見報錯與解決方案1. 報錯&#xff1a;could not find function "bitr"2. 報錯&#xff1a…

【轉】PostgreSql的鏡像地址

docker.io/postgres 項目中國可用鏡像列表 | 高速可靠的 Docker 鏡像資源 docker.io/postgrest/postgrest:v12.2.8 linux/amd64 docker.io17.34MB2025-04-04 13:14 346 docker.io/postgrest/postgrest:v12.2.12 linux/amd64 docker.io17.38MB2025-05-27 22:02 79 docker.io…

爬蟲005----Selenium框架

在總結爬蟲 &#x1f577; 框架之前&#xff0c;先總結一下selenium框架&#xff0c;也可以說是selenium庫&#xff0c;在自動化測試中是老生常談了&#xff08;長時間??不用&#xff0c;已經忘記了&#xff0c;實際測試工作中做UI自動化的也很少了&#xff0c;上次搞UI自動化…

記一次 Kafka 磁盤被寫滿的排查經歷

開篇扯犢子 今天踏進辦公聽到不是同事的早安&#xff0c;而是“有一個好消息&#xff0c;一個壞消息&#xff0c;你想聽哪個&#xff1f;” 我一愣&#xff0c;心想“大早上&#xff0c;就要玩刺激的嗎&#xff1f;” 但是還是淡定的回復說“無所謂&#xff0c;哥什么場面沒見…

python多線程:各線程的輸出在控制臺中同一行原因分析

代碼例子 import threading import timedef error_worker():print("子線程開始")time.sleep(1)raise Exception("子線程出錯了&#xff01;")t threading.Thread(targeterror_worker) t.start()print("主線程繼續執行&#xff0c;不受子線程異常影響…

Promptify與ReActAgent

一、Promptify 定位&#xff1a;NLP 任務的「自動化流水線」 1. 解決什么問題&#xff1f; 傳統 LLM 應用開發痛點&#xff1a; 反復調試&#xff1a;需手工編寫/調整 prompt 格式&#xff08;如調整分隔符、示例數量&#xff09;兼容性差&#xff1a;不同模型需重寫適配代碼…

如何將視頻從 iPhone 發送到 Android 設備

如果您想將視頻從 iPhone 發送到 Android 設備&#xff0c;尤其是視頻尺寸較大時&#xff0c;您需要一種高效的傳輸方法。本文將為您提供 7 種實用方法&#xff0c;讓您輕松發送大型視頻文件或短視頻片段&#xff0c;并且不會損失視頻質量。 第 1 部分&#xff1a;如何通過 iRe…

Stable Diffusion入門-ControlNet 深入理解 第四課:風格遷移與重繪控制模型——讓AI也有“藝術天賦”!

大家好&#xff0c;歡迎回到 Stable Diffusion入門-ControlNet 深入理解 系列的第四課&#xff01; 如果你還沒有看過上一課&#xff0c;趕緊補課哦&#xff1a;Stable Diffusion入門-ControlNet 深入理解 第三課。 上一課我們講解了 ControlNet 結構類模型&#xff0c;今天我…

國產鴻蒙系統開放應用側載,能威脅到Windows地位嗎?

上個月華為正式發布了 HarmonyOS PC 操作系統&#xff0c;關于生態方面大家其實一直蠻擔心。 例如不兼容Windows應用、不支持應用側載等。 不過&#xff0c;在最近舉行的華為開發者大會 2025 電腦分論壇上&#xff0c;華為終端 BG 平板與 PC 產品線總裁&#xff08;朱懂東&am…

Linux登錄檢查腳本

登錄檢查腳本 提高兼容性&#xff08;適應不同Linux發行版&#xff09;增強可視化效果和可讀性增加關鍵資源警戒提示優化表格對齊和顏色使用添加系統安全狀態檢查 #!/bin/bash# 改進版系統登錄提示腳本 # 優化點&#xff1a;兼容性增強、資源警戒提示、表格美化、安全狀態檢查…

jenkinsfile調用groovy

先決條件 gitlab存放jenkinsfile以及groovy代碼,jenkins我個人使用的是2.486具體的部署方法自己搞定,一堆文檔. gitlab創建一個devops8項目組以及my-jenkins-demo2項目用于演示過程 創建群組 這里已經創建好相關群組. 進入群組創建新項目 創建一個空白項目 配置項目選項 說明…

Ubuntu20.04離線安裝Realtek b852無線網卡驅動

最近有個項目&#xff0c;需要在 Ubuntu20.04 LTS 下開發&#xff0c;首先是安裝 Linux&#xff0c;我們可以從下面的網址下載&#xff1a; https://releases.ubuntu.com/20.04/ 本以為一切順利&#xff0c;結果剛開始就給我整不會了。我的電腦是聯想設計師GeekPro7&#xff…

1 Studying《Computer Architecture A Quantitative Approach》5-7

目錄 5 Thread-Level Parallelism 5.1 Introduction 5.2 Centralized Shared-Memory Architectures 5.3 Performance of Symmetric Shared-Memory Multiprocessors 5.4 Distributed Shared-Memory and Directory-Based Coherence 5.5 Synchronization: The Basics 5.6 M…

融智興科技: RFID超高頻柔性抗金屬標簽解析

在當今科技飛速發展的時代&#xff0c; RFID技術憑借其獨特的優勢&#xff0c;在眾多領域得到了廣泛應用。然而&#xff0c;在金屬環境中&#xff0c;傳統RFID標簽往往面臨著諸多挑戰&#xff0c;如信號干擾、識別距離短等問題。融智興科技推出的RFID 超高頻柔性抗金屬標簽&…

PHP Error: 深入解析與解決策略

PHP Error: 深入解析與解決策略 引言 PHP作為世界上最流行的服務器端腳本語言之一,在全球范圍內被廣泛使用。然而,在PHP的開發過程中,錯誤處理是一個非常重要的環節。本文將深入探討PHP錯誤處理的相關知識,包括錯誤類型、錯誤配置、錯誤日志以及常見的錯誤解決策略。 PH…

零基礎langchain實戰二:大模型輸出格式化成json

零基礎langchain實戰一&#xff1a;模型、提示詞和解析器-CSDN博客 書接上文 大模型輸出格式化 在下面例子中&#xff1a;我們需要將大模型的輸出格式化成json。 import os from dotenv import load_dotenvload_dotenv() # 加載 .env 文件 api_key os.getenv("DEEPS…

高通手機跑AI系列之——人臉變化算法

環境準備 手機 測試手機型號&#xff1a;Redmi K60 Pro 處理器&#xff1a;第二代驍龍8移動--8gen2 運行內存&#xff1a;8.0GB &#xff0c;LPDDR5X-8400&#xff0c;67.0 GB/s 攝像頭&#xff1a;前置16MP后置50MP8MP2MP AI算力&#xff1a;NPU 48Tops INT8 &&…