简体   繁体   中英

How to add new row when user press enters on last column of DataGridView in C#

  • How do I jump to the next row when user presses enter on the last column of DataGridView ?

  • This code also gives me an error which I need to resolve:

    Index is out of range must be non-negative and less than the size of collection.

     private void DataGridView1_KeyDown(object sender, KeyEventArgs e) { try { if (e.KeyCode == Keys.Enter) { e.SuppressKeyPress = true; int iColumn = DataGridView1.CurrentCell.ColumnIndex; int iRow = DataGridView1.CurrentCell.RowIndex; if (iColumn >= DataGridView1.Columns.Count - 2) DataGridView1.CurrentCell = DataGridView1[0, iRow + 1]; else DataGridView1.CurrentCell = DataGridView1[iColumn + 1, iRow]; } } catch (Exception ex) { MessageBox.Show(ex.Message.ToString()) } } 

You could handle this using DataGridView.KeyDown , but you would miss the case where the user hits Enter while editing a cell. To catch all cases, derive your own class from DataGridView and override ProcessCmdKey . Using the logic suggested in comments above, when Enter is detected for the last Row, add another row. Don't worry about manually changing the CurrentCell . Let the base class handle that work itself.

public class MyDataGridView : DataGridView
{
    protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {
        bool enterKeyDetected = keyData == Keys.Enter;
        bool isLastRow = this.CurrentCell.RowIndex == this.RowCount - 1;

        if (enterKeyDetected && isLastRow)
        {
            Console.WriteLine("Enter detected on {0},{1}", this.CurrentCell.RowIndex, this.CurrentCell.ColumnIndex);

            // Add the new row.
        }

        return base.ProcessCmdKey(ref msg, keyData);
    }
}

You need only pay attention to how you add the new row depending on your DataSource :

  • None

     this.Rows.Add(); 
  • A DataTable

     DataTable dt = (DataTable)this.DataSource; dt.Rows.Add(); 
  • A BindingList<T> (see List vs BindingList )

     BindingList<T> bl= (BindingList<T>)this.DataSource; bl.Add(new T()); 
  • Etc.

Lastly, just replace your instance of DataGridView with an instance of this custom one.


All that said, if you don't have a DataSource , just setting DataGridView.AllowUserToAddRows = true should suffice since editing the NewRow will trigger another to be added.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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