首页 > 其他分享 >Winform中给DataGridView添加多选框列并获取选中行的内容

Winform中给DataGridView添加多选框列并获取选中行的内容

时间:2023-03-12 10:31:44浏览次数:41  
标签:Rows int Cells DataGridView 选中 dataGridView1 选框 Winform


场景

使用NPOI导入Excel并赋值给DataTable,然后显示在DataGrdView上,并且添加多选框,然后获取选中行的内容。

Winform中使用NPOI实现Excel导入并赋值给DataTable:

实现

给DataGridView添加多选框,而不是给DataTable添加多选框。

DataGridViewColumn checkCol = new DataGridViewCheckBoxColumn();
this.dataGridView1.Columns.Add(checkCol);

获取选中行的内容

private void button4_Click(object sender, EventArgs e)
{


int strCount = 0;
//首先进行第一次循环 获取选中的行数
for (int i = 0; i <dataGridView1.Rows.Count; i++)
{
//如果被选中
if ((bool)dataGridView1.Rows[i].Cells[0].EditedFormattedValue == true)
{
strCount++;
}
}
//新建 选中长度的数组存放每一行
string[] str = new string[strCount];
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
if ((bool)dataGridView1.Rows[i].Cells[0].EditedFormattedValue == true)
{
//获取当前行的第一个单元格 + @ +第二个单元格的内容
str[i] = dataGridView1.Rows[i].Cells[1].Value.ToString() + "@" + dataGridView1.Rows[i].Cells[2].Value.ToString();
}
}
//输出选中所有行的内容
for (int i = 0; i < str.Length; i++)
{
MessageBox.Show(string.Format("获取的第{0}条为:",i+1) +str[i]);
}

}

效果

Winform中给DataGridView添加多选框列并获取选中行的内容_i++

 

标签:Rows,int,Cells,DataGridView,选中,dataGridView1,选框,Winform
From: https://blog.51cto.com/BADAOLIUMANGQZ/6115516

相关文章