Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I set the Max number of rows in unbound DataGridView

I find it hard to believe this hasn't been asked before, but it doesn't appear like it has been and my Google searches have all been for naught.

Can I set a maximum number of rows that a DataGridView will allow a user to add? (Like after adding the 10th row it will no longer display the 'new row' row?).

like image 524
Chris Pfohl Avatar asked Mar 05 '11 19:03

Chris Pfohl


1 Answers

There is no direct property to do this, but you should be able to accomplish this pretty easily using a combination of the AllowUserToAddRows property, and the UserAddedRow event.

The general idea is to add an event handler to check the number of rows against the Maximum Allowed, and then set AllowUserToAddRows = false

public partial class frmGridWithRowLimit : Form
{
    public Int32 MaxRows { get; set; }

    public frmGridWithRowLimit()
    {
        MaxRows = 10;

        InitializeComponent();

        dgRowLimit.UserAddedRow += dgRowLimit_RowCountChanged;
        dgRowLimit.UserDeletedRow += dgRowLimit_RowCountChanged;
    }

    private void dgRowLimit_RowCountChanged(object sender, EventArgs e)
    {
        CheckRowCount();
    }

    private void CheckRowCount()
    {
        if (dgRowLimit.Rows != null && dgRowLimit.Rows.Count > MaxRows)
        {
            dgRowLimit.AllowUserToAddRows = false;
        }
        else if (!dgRowLimit.AllowUserToAddRows)
        {
            dgRowLimit.AllowUserToAddRows = true;
        }
    }
}

You will also want to handle when a user deletes a row to make sure that you allow them to add rows again.

Hope this helps

Cheers, Josh

like image 107
Josh Avatar answered Nov 14 '22 21:11

Josh