Winform中实现List<string>赋值给dataGridView与实现多选、全选和获取选择的内容
生活随笔
收集整理的這篇文章主要介紹了
Winform中实现List<string>赋值给dataGridView与实现多选、全选和获取选择的内容
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
場景
Winform中給DataGridView添加多選框列并獲取選中行的內容:
Winform中給DataGridView添加多選框列并獲取選中行的內容_BADAO_LIUMANG_QIZHI的博客-CSDN博客
在上面的基礎上,實現(xiàn)了添加多選框并獲取選中行的內容。
如果要將List<string>作為dataGridView的數據源并實現(xiàn)多選和全選以及獲取選擇的內容怎么實現(xiàn)。
注:
博客:
BADAO_LIUMANG_QIZHI的博客_CSDN博客
關注公眾號
霸道的程序猿
獲取編程相關電子書、教程推送與免費下載。
實現(xiàn)
1、將List<string>賦值給dataGridView的數據源
this.dataGridView_show_tables_name.DataSource = this.tableNameList.Select(x => new { Value = x }).ToList();其中tableNameList就是List<string>
2、實現(xiàn)多選框
??????????? DataGridViewColumn checkCol = new DataGridViewCheckBoxColumn();checkCol.Name = "選擇";this.dataGridView_show_tables_name.Columns.Add(checkCol);3、實現(xiàn)全選
首先添加一個checkbox作為全選選擇框
然后實現(xiàn)其changed事件
??????? private void checkBox1_CheckedChanged(object sender, EventArgs e){if (this.checkBox_select_all.Checked == true){for (int i = 0; i < this.dataGridView_show_tables_name.Rows.Count; i++){this.dataGridView_show_tables_name.Rows[i].Cells["選擇"].Value = 1;}}else{for (int i = 0; i < this.dataGridView_show_tables_name.Rows.Count; i++){this.dataGridView_show_tables_name.Rows[i].Cells["選擇"].Value = 0;}}}在上面添加checkCol時設置了其Name屬性。,所以這里通過Cells[|"選擇"]獲取到對應列。
4、獲取選擇的內容
首先聲明變量來接收獲取的內容
List<string> selectedTableNameList = new List<string>();然后再需要獲取選擇內容的地方
??????????? this.selectedTableNameList.Clear();for (int i = 0; i < this.dataGridView_show_tables_name.Rows.Count; i++){if ((bool)this.dataGridView_show_tables_name.Rows[i].Cells["選擇"].EditedFormattedValue == true){selectedTableNameList.Add(this.dataGridView_show_tables_name.Rows[i].Cells[1].Value.ToString());}} 與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的Winform中实现List<string>赋值给dataGridView与实现多选、全选和获取选择的内容的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ERROR 2059 (HY000):
- 下一篇: Winform中实现点击按钮弹窗输入密码