DataGridView with limited number of rows

I need to have a datagridview with limited number of rows. The user can add rows by directly typing in the cell and also by using a button. I have gone through similar questions on internet and used the code there but it doesn't work properly.

Currently in the code I am posting, it works correctly until I start typing in the last row and then I get stack overflow exception.

Any help is appreciated. Thanks in advance.

    int maxNumberOfRows = 6;

    private void dgv1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
    {
        CheckRowCount();
    }

    private void dgv1_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
    {
        CheckRowCount();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        if (dgv1.Rows.Count < maxNumberOfRows)
            dgv1.Rows.Add("Row added by button");
        else
            dgv1.Rows[dgv1.CurrentCell.RowIndex].Cells[0].Value = "Row added by button";
    }

    private void CheckRowCount()
    {
        if (dgv1.Rows.Count <= maxNumberOfRows)
            dgv1.AllowUserToAddRows = true;
        else
            dgv1.AllowUserToAddRows = false;
    }

1 answer

  • answered 2019-10-08 08:08 ZedLepplin

    Change if (dgv1.Rows.Count <= maxNumberOfRows) to if (dgv1.Rows.Count < maxNumberOfRows)

    Remove the = character.