c# datagridview 如何选中行,以及怎么获取选中行的数据

2024-01-11 13:47:41
推荐回答(4个)
回答1:

C#如何获取DataGridView对象单元格的内容,这里介绍下获取方法。

1、首先需要在事件列表中找到DataGridView对象的CellClick事件。

2、然后在此事件中,会有DataGridCiewCellEventArgs事件变量e。

3、此时便能利用DataGridCiewCellEventArgs事件变量e的RowIndex属性获得行索引,但是我们需要加1。

4、并且还能通过CurrentCellAddress属性组的X和Y坐标,也是能够获得行列索引。

回答2:

可以设置DataGridView的SelectionMode属性为FullRowSelect 实现左键点击选取整行,右击的话就需要在鼠标点击事件里面实现了
如下:
private void dataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.ColumnIndex < 0 || e.RowIndex < 0) return;
if (e.Button == System.Windows.Forms.MouseButtons.Right)
{
dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Selected = true;
}
}
右键菜单自己设置关联上dgv就可以,右键菜单的按钮点击事件内容如下:
if (dataGridView1.CurrentRow == null) return;
DataGridViewRow dgvr = dataGridView1.CurrentRow;
string val = dgvr.Cells["???"].Value.ToString();你自己要获取的数据

扩展内容

c#怎么获取datagridview选中多行的每一行中的某一列的值

var datagridview = new DataGridView();
var dataselect = datagridview.SelectedRows;
var label = new Label();
foreach (DataGridViewRow row in dataselect)
{
label.Text += row.Cells[1].Value + "\n";
}
c# datagridview 如何选中行-搜狗百科

回答3:

可以设置DataGridView的SelectionMode属性为FullRowSelect 实现左键点击选取整行,右击的话就需要在鼠标点击事件里面实现了
如下:
private void dataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.ColumnIndex < 0 || e.RowIndex < 0) return;
if (e.Button == System.Windows.Forms.MouseButtons.Right)
{
dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Selected = true;
}
}
右键菜单自己设置关联上dgv就可以,右键菜单的按钮点击事件内容如下:
if (dataGridView1.CurrentRow == null) return;
DataGridViewRow dgvr = dataGridView1.CurrentRow;
string val = dgvr.Cells["???"].Value.ToString();你自己要获取的数据

回答4:

赞同一楼的做法.选定FullRowSelect.