Reputation: 945
I am new to c# and using windows forms.
I was looking for an event to use with datagridview
when arrow down key in the keyboard is pressed and I found keyDown datagridview
event.
What I am trying to do is:
let's say I have datagridview
with 4 rows
, now when I press arrow down (in the keyboard) I want the highlight (selection) go down and on same time when a row is selected I want the event to check if the row font color is red or not so I used the following code:
private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
{
int RowIndex = dataGridView1.SelectedRows[0].Index;
if (dataGridView1.Rows[RowIndex].DefaultCellStyle.ForeColor == Color.Red)
{
MessageBox.Show("This row font is red");
}
}
When I tried this code it does not work well, the problem is:
Say:
Row0 font color = black
Row1 font color = red
Row2 font color = black
Row3 font color = black
Now the selected row is Row0
, press arrow down it goes to Row1
but the event doesn't get fired. Now the selected row is Row1
and when I press arrow down the event works but too late, I mean it should get fired when Row1
is selected.
Anyone knows how can I fix it (or any other ideas)? I just want to check rows font color when I press arrow key down in keyboard? Thank you
Upvotes: 0
Views: 1621
Reputation: 25
to achieve this you can use SelectionChanged event first set the row selection mode with following line
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
then here is the selection changed event mechanism
private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
if (dataGridView1.SelectedRows.Count > 0)
{
int RowIndex = dataGridView1.SelectedRows[0].Index;
if (dataGridView1.Rows[RowIndex].DefaultCellStyle.ForeColor == Color.Black)
{
MessageBox.Show("This row font is Black");
}
}
}
Upvotes: 1