none
DataGridView Cell Control movement RRS feed

  • Question

  • How can I control the cursor movement within a datagridview in VS 2008. I want the crusor to move right instead of down after the enter key is hit.
    Wednesday, January 2, 2013 4:12 AM

Answers

  • You could use the KeyDown event to do that:
    
    private void DataGridView1_KeyDown(object sender, KeyEventArgs e)
            {
                if (e.KeyCode == Keys.Enter)
                {
    				DataGridView vw = (DataGridView)sender;
                    if (vw.CurrentCell.RowIndex == vw.Rows.Count - 1)
                    {
                        if (vw.CurrentCell.ColumnIndex != vw.ColumnCount - 1)
                        {
                            vw.CurrentCell = vw.Rows[vw.CurrentCell.RowIndex].Cells[vw.CurrentCell.ColumnIndex + 1];
                        }
                        else
                        {
                            vw.Rows.Add(1);
                            vw.Refresh();
                            SendKeys.Send("{HOME}");
                        }
                    }
                    else
                    {
                        if (vw.CurrentCell.ColumnIndex == vw.ColumnCount - 1)
                        {
                            vw.CurrentCell = vw.Rows[vw.CurrentCell.RowIndex + 1].Cells[0];
                        }
                        else
                        {
                            vw.CurrentCell = vw.Rows[vw.CurrentCell.RowIndex].Cells[vw.CurrentCell.ColumnIndex];
                        }
                    }
       e.Handled = true;
     }
    }
    
    

    Nordine Ben Bachir Trainer & Consultant MCPD .NET4, 3.5, 2.0

    Wednesday, January 2, 2013 9:27 AM