简体   繁体   中英

Getting the first cell from selected row from DataGridView in C#

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();
}

Which gets me the following error:

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?

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);
  }
}

Why you were getting the "Index was out of range." error is already explained by JohnG very well.

I have another simple way of doing what you are trying here.

C# DataGridView has one parameter CurrentRow

It also works even if only a cell is selected and not an entire row. But if multiple rows are selected, it will only get you the last selected row's first cell.

private void exec_cmd_btn_Click(object sender, EventArgs e)
{
    string cell = dataGridView1.CurrentRow.Cells[0].Value.ToString();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM