Question

How Can Add and Remove Rows based on the value of the numericupdown value??

i've tried creating this;

private void numericUpDown1_ValueChanged(object sender, EventArgs e)
        {
            dataGridView1.Rows.Add();
        }

It adds correctly, however, when I decrease the value it keeps adding again!!!

Yeah I know it is really wrong because it always add whenever the numericupdownvalue is altered.

What i'm asking is that is there a increase property and decrease property in a numeric control? Is there a way to solve my problem?

Btw, I've set the numericupdown value to 1 so that 1 is the default value.

PLEASE PLEASE!!!

Was it helpful?

Solution

Don't forget that numeric up down controls can be edited directly, so when the value changes there's no guarantee that you're just one row different from where you were before.

You need to change the number of rows until it matches the current value of the numeric control. Something like this:

private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
    // presuming numericUpDown1 cannot have a value below zero

    // Note that when dataGridView1.Rows.Count == numericUpDown1.Value
    // these loops will do nothing, as we would want...
    while (dataGridView1.Rows.Count < numericUpDown1.Value)
    {
        dataGridView1.Rows.Add();
    }
    while (dataGridView1.Rows.Count > numericUpDown1.Value)
    {
        dataGridView1.Rows.RemoveAt(dataGridView1.Rows.Count - 1);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top