C# 如何在选择更改时获取 DataGridView 中的特定单元格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/404651/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get a specific cell in a DataGridView on selection changed
提问by Elie
With a listbox, I have the following code to extract the item selected:
使用列表框,我有以下代码来提取所选项目:
private void inventoryList_SelectedIndexChanged(object sender, EventArgs e)
{
String s = inventoryList.SelectedItem.ToString();
s = s.Substring(0, s.IndexOf(':'));
bookDetailTable.Rows.Clear();
...
more code
...
}
I want to do something similar for a DataGridView, that is, when the selection changes, retrieve the contents of the first cell in the row selected. The problem is, I don't know how to access that data element.
I want to do something similar for a DataGridView, that is, when the selection changes, retrieve the contents of the first cell in the row selected. 问题是,我不知道如何访问该数据元素。
Any help is greatly appreciated.
任何帮助是极大的赞赏。
采纳答案by Mitchell Gilman
I think that this is what you're looking for. But if not, hopefully it will give you a start.
我认为这就是你要找的。但如果没有,希望它会给你一个开始。
private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
DataGridView dgv = (DataGridView)sender;
//User selected WHOLE ROW (by clicking in the margin)
if (dgv.SelectedRows.Count> 0)
MessageBox.Show(dgv.SelectedRows[0].Cells[0].Value.ToString());
//User selected a cell (show the first cell in the row)
if (dgv.SelectedCells.Count > 0)
MessageBox.Show(dgv.Rows[dgv.SelectedCells[0].RowIndex].Cells[0].Value.ToString());
//User selected a cell, show that cell
if (dgv.SelectedCells.Count > 0)
MessageBox.Show(dgv.SelectedCells[0].Value.ToString());
}
回答by seem7teen
This is another way of approaching to this question using the column name.
这是使用列名解决此问题的另一种方法。
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
var senderGrid = (DataGridView)sender;
if (senderGrid.Columns[e.ColumnIndex] is DataGridViewButtonColumn && e.RowIndex >= 0)
{
if (e.ColumnIndex == dataGridView1.Columns["ColumnName"].Index)
{
var row = senderGrid.CurrentRow.Cells;
string ID = Convert.ToString(row["columnId"].Value); //This is to fetch the id or any other info
MessageBox.Show("ColumnName selected");
}
}
}
If you need to pass the data from that selected row you can pass it this way to the other form.
如果您需要从所选行传递数据,您可以通过这种方式将其传递给另一个表单。
Form2 form2 = new Form2(ID);
form2.Show();