在GridView中管理选项卡索引

时间:2013-03-30 13:25:54

标签: winforms gridview key-value tabindex

我在gridview中有3列 - 代码,数量,名称。如果是单元格(Say Code),处于编辑模式,按箭头或Tab键将触发'CellEndEdit'事件,然后移动选择到下一个细胞。我想要有不同的选定单元格,如果它是一个箭头键而另一个被选中,如果它是制表符。例如:
在右箭头键上:代码 - >数量
按Tab键:代码 - >名称

一旦单元格进入编辑模式,datagridview的键事件(向下,向上,按下)不会触发。因此,当单元格处于编辑模式时,如何获取最后按下的键的值。我必须在CellEndEdit事件中编写代码/方法/函数。这可能是这样的:

private void DataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)       
{  
  //Some calculations;  
  //Get the key if it is tab or arrow to decide which cell should be selected next  
 If((bool)OnKeyDown()==true)   
    then do this;
}          
void OnKeyDown(KeyEventArgs e)
 { 
   if(e.KeyValue==9)//tab key     
     return true;
 }

2 个答案:

答案 0 :(得分:0)

使用此link的解决方案,我能够提出一些可以帮助您的方法。

首先,您要创建自己的用户类,该用户类派生自DataGridView并覆盖ProcessCmdKey函数。无论您的单元格是否处于编辑模式,都会调用此函数。

public partial class MyDataGridView : DataGridView
{
    protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {
        if (keyData == Keys.Tab)
        {
            this.CurrentCell = this.Rows[this.CurrentCell.RowIndex].Cells[1];
            return true;
        }
        else if (keyData == Keys.Right)
        {
            this.CurrentCell = this.Rows[this.CurrentCell.RowIndex].Cells[2];
            return true;
        }
        else
            return base.ProcessCmdKey(ref msg, keyData);
    }
}

您现在需要做的就是更改此函数内部的逻辑,根据已按下的键转到相应的列,并使用此自定义类而不是默认的DataGridView

答案 1 :(得分:0)

我基于soln以这种方式解决了这个问题。这里:
http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/0283fe97-c0ad-4768-8aff-cb4d14d48e15/

bool IsTabKey;
private void DataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)       
{  
   //Some calculations;  
  //Get the key if it is tab or arrow to decide which cell should be selected next  
    If(IsTabKey==true)   
      //then do this;
}  
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    if(GridViewSale.CurrentCell.ColumnIndex == 1 && keyData == Keys.Tab)
       IsTabKey = true;
       return false;
}