简体   繁体   English

为什么KeyDown事件不能与datagridview c#一起使用?

[英]Why KeyDown event is not working with datagridview c#?

I am new to c# and using windows forms. 我是C#和使用Windows窗体的新手。

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. 当我按下键盘上的向下箭头键并找到keyDown datagridview事件时,我正在寻找一个与datagridview一起使用的事件。

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: 假设我有4 rows datagridview ,现在当我按下箭头(在键盘上)时,我希望突出显示(选择)下降,并且在选择行的同时,我希望事件检查行字体颜色是否为是否为红色,所以我使用以下代码:

 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. 现在选定的行是Row0 ,向下按箭头将转到Row1但不会触发该事件。 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. 现在选定的行是Row1 ,当我按下箭头向下时,该事件有效,但为时已晚,我的意思是当选择Row1时应将其触发。

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 谢谢

The KeyDown event fires before the selection actually has changed. 实际更改选择之前会触发KeyDown事件。

Key events occur in the following order: 关键事件按以下顺序发生:

 KeyDown KeyPress KeyUp 

So a simple solution is to move your code to the KeyUp event, which happens after the new row selection has happened. 因此,一个简单的解决方案是将代码移至KeyUp事件,该事件选择新行之后发生。

to achieve this you can use SelectionChanged event first set the row selection mode with following line 为此,您可以使用SelectionChanged事件首先通过以下行设置行选择模式

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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