在Datagridview输入键按下选择转到下一行但我想转到下一列?

时间:2015-08-07 05:29:18

标签: c# winforms datagridview

DataGridView输入键按键选择转到下一行但我想转到下一列?怎么解决它?

private void textBox1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{       
   if (e.KeyCode == Keys.Enter)
   {
   }
}

1 个答案:

答案 0 :(得分:1)

DataGridView中有一个名为CurrentCell的属性,因此您应该使用它:

    private void dataGridView1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            int newRow;
            int newColumn;
            if (dataGridView1.CurrentCell.ColumnIndex == dataGridView1.ColumnCount-1)         // it's a last column, move to next row;
            {
                newRow = dataGridView1.CurrentCell.RowIndex + 1;
                newColumn = 0;

                if (newRow == dataGridView1.RowCount)
                    return; // ADD new row or RETURN (depends of your purposes..)
            }
            else                // just change current column. row is same
            {
                newRow = dataGridView1.CurrentCell.RowIndex;
                newColumn = dataGridView1.CurrentCell.ColumnIndex + 1;
            }

            dataGridView1.CurrentCell = dataGridView1.Rows[newRow].Cells[newColumn];
        }
    }