Reputation: 731
I want to know how to check whether a gridview's row got selected or not. I am working on windows application.
I want to put a if condition ie if a particular row gets selected then fill the textbox with the correspoding cell value.
I am just not getting the way how to give the condition in the if clause.
Upvotes: 1
Views: 17693
Reputation: 14781
Handle the DataGridView.SelectionChanged event. Use the DataGridView.SelectedRows property to get the selected rows collection.
private void dataGridView_SelectionChanged(object sender, EventArgs e)
{
// Update the text of TextBox controls.
textBox1.Text = dataGridView.SelectedRows[0].Cells[1].Value.ToString();
textBox2.Text = dataGridView.SelectedRows[0].Cells[2].Value.ToString();
....
}
Upvotes: 3
Reputation: 4754
You can subscribe to the SelectionChanged event of the control and iterate through each selected row if multi-selection is enabled or just the first one if single-row selection only.
private void MyGridView_SelectionChanged(object sender, EventArgs e)
{
for (int i = 0; i < MyGridView.SelectedRows.Count; i++)
{
MyTextBox.Text = MyGridView.SelectedRows[i].Cells[0].Value.ToString(); //assuming column 0 is the cell you're looking for
// do your other stuff
}
}
More information can be found on the SelectedRows property.
Upvotes: 0
Reputation: 6637
Check the selected property of DataGridViewRow
, it returns true
for selected else false
.
bool isSelected = dataGridView1.Rows[e.RowIndex].Selected;
Upvotes: 0
Reputation: 14781
Check DataGridViewRow.Selected property.
if (dataGridView.Rows[rowIndex].Selected)
{
// Do something ..
}
Upvotes: 0