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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With