从C#中的DataGridView中从选定的行中获取第一个单元格 [英] Getting the first cell from selected row from DataGridView in C#
问题描述
我有一个连接到mssql数据库的datagridview,我想在按 exec_cmd_btn
时从选定的行中获取第一个单元格到目前为止,我已经尝试过:
I have a datagridview connected to a mssql database and i want to get the first cell from selected row when i press exec_cmd_btn So far i have tried:
private void exec_cmd_btn_Click(object sender, EventArgs e)
{
string cell = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
}
哪个会给我以下错误:
索引超出范围。参数名称:index
Index was out of range. Must be non-negative and less than the size of the collection.\r\nParameter name: index
是否必须为负数,且必须小于集合的大小?
Do I need to create an event for when I press on the data grid view?
推荐答案
我猜您可能会遇到问题吗? SelectedRows
属性,因为这取决于 DataGridView
的 SelectionMode $ c $的方式c>已设置。如果
DataGridViews
SelectionMode
未设置为 FullRowSelect
,则此实现不管用。由于您正在尝试从第一列获取单元格,因此,我想这不会成为问题,因为您要确保也选择了第一列。另一个问题是,如果 DataGridView
MultiSelect
属性设置为true,则使用 SelectedRows的代码[0]
将返回最后选择的行,而不是第一行。如果要选择第一行,则可以使用下面的代码。它将显示所选的第一行和最后一行。希望这会有所帮助。
I am guessing you may be running into an issue with the SelectedRows
property, as this depends on how the DataGridView
’s SelectionMode
is set. If the DataGridViews
SelectionMode
is not set to FullRowSelect
this implementation will not work. Since you are trying to get the cell from column one, then I would not think this would be a problem since you want to make sure that the first column is also selected. Another issue is if the DataGridView
MultiSelect
property is set to true, then your code using SelectedRows[0]
will return the LAST selected row, not the first. If you want the first selected row then you can use the code below. It will display the first and last rows selected. Hope this helps.
// The DataGridView SelectionMode must be set 'FullRowSelect' for this to work!
private void button1_Click(object sender, EventArgs e) {
if (dataGridView1.SelectedRows.Count > 0) {
int firstRowIndex = dataGridView1.SelectedRows.Count - 1;
string cell = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
string cell2 = dataGridView1.SelectedRows[firstRowIndex].Cells[0].Value.ToString();
MessageBox.Show("Last selected row at cell[0] value: " + cell + " First Selected row at cell[0] value: " + cell2);
}
}
这篇关于从C#中的DataGridView中从选定的行中获取第一个单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!