Если DataGridView пуст, при клике на его заголовок возникает ошибка.
Решение:
The error is quite clear - your dgvProfiles_CellClick method is being passed a RowIndex which is not valid.
That's because you've clicked on the header, not a row. The CellClick fires for both, and passes a RowIndex of -1 when you click the header.
Change your code to ignore the event when you click on the header:
private void dgvProfiles_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex == -1) return;
DataGridViewRow row = dgvProfiles.Rows[e.RowIndex];
...
}Второй способ
private void dataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.RowIndex >= 0)
{
DataGridViewRow row = dataGridView1.Rows[e.RowIndex];
txtID.Text = row.Cells[0].Value.ToString();
txtName.Text = row.Cells[1].Value.ToString();
txtCountry.Text = row.Cells[2].Value.ToString();
}
}Данный код добавляет текст из dataGridView1 в текстовые поля при клике.
To get one cell value based on entire row selection:
if (dataGridView1.SelectedRows.Count > 0)
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
TextBox1.Text = row.Cells["ColumnName"].Value.ToString();
}
}
else
{
MessageBox.Show("Please select item!");
}
}