Can I set the maximum number of rows in an unbound DataGridView

It’s hard for me to believe that they didn’t ask this before, but it doesn’t look like it was, and my Google searches were with nothing.

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

+7
source share
1 answer

There is no direct property for this, but you should easily accomplish this with a combination of the AllowUserToAddRows property, and UserAddedRow .

The general idea is to add an event handler to check the number of rows in 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 process when the user deletes the row to make sure that you allow them to add the rows again.

Hope this helps

Cheers, Josh

+9
source

All Articles