0

I have a DataGridView(DGV) control in my winform. The DGV has 4 columns. First 2 columns are of Combobox type and the rest 2 are of Textbox type.When i press Enter key in any cell, then it moves on to the next cell.While at the last cell if Enter is pressed then a new row is created and the focus moves on the first column of the second row.And i want it to always behave in that manner.My problem begins when i set 'Enable Editing'=true.With enable editing=true, whenever i select any item from combobox in the first column, an unnecessary New row is created.I don't want a new row to be created at this point.Please advise how to avoid this.

private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyData == Keys.Enter)
    {
        int col = dataGridView1.CurrentCell.ColumnIndex;
        int row = dataGridView1.CurrentCell.RowIndex;

        if (col < dataGridView1.ColumnCount - 1)
        {
            col++;
        }
        else
        {
            col = 0;
            row++;
        }

        if (row == dataGridView1.RowCount)
            dataGridView1.Rows.Add();

        dataGridView1.CurrentCell = dataGridView1[col, row];
        e.Handled = true;
    }
}
gomesh munda
  • 838
  • 2
  • 14
  • 32
  • _"whenever i select any item from combobox in the first column, an unnecessary New row is created."_ Is the function you posted the code that is creating the new row? If so, use a breakpoint and check the call stack to see what else is being triggered. – Steve Wellens Mar 27 '16 at 04:11
  • Not actually.The above code just moves the cursor from column to column on pressing Enter and while at last column creates a valid new row – gomesh munda Mar 27 '16 at 04:13
  • Yes, I know it creates a new row. So if _that_ isn't creating the new row, you'll have to look elsewhere. – Steve Wellens Mar 27 '16 at 04:33
  • Well... i guess it must be a default behavior and i will have to live with that :) – gomesh munda Mar 27 '16 at 04:43

1 Answers1

3

In your DataGridView control, set the AllowUserToAddRows property to False. This does NOT stop you from programmatically adding rows through your own custom event model. It simply will disable those auto-generated rows you might be having trouble with.

Jace
  • 777
  • 1
  • 5
  • 18
  • i can't see the said property in the properties window. :( – gomesh munda Mar 27 '16 at 05:14
  • Sorry, the property is AllowUserToAddRows... https://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.allowusertoaddrows%28v=vs.110%29.aspx – Jace Mar 27 '16 at 06:16