开发者

Can I set the Max number of rows in unbound DataGridView

开发者 https://www.devze.com 2023-02-14 20:47 出处:网络
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.

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?).


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

0

精彩评论

暂无评论...
验证码 换一张
取 消