How to remove the last DataGridViewRow when inserting a new one at the beginning?

212 views Asked by At

Using a Windows Forms application.
I have this class, derived from a DataGridView control:

public class CustomDataGridView : DataGridView
{
    private int maxRowsAllowed = 3;

    public CustomDataGridView()
    {
        this.AutoGenerateColumns = false;
        this.AllowUserToAddRows = false;
        this.AllowUserToDeleteRows = false;
        this.ReadOnly = true;
        this.RowsAdded += CustomDataGridView_RowsAdded;
        this.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
    }

    public void Start()
    {
        this.Columns.Add("col1", "header1");
        this.Columns.Add("col2", "header2");

        // rows added manually, no DataSource
        this.Rows.Add(maxRowsAllowed);
    }

    private void customDataGridView_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
    {
        // At this point, while debugging, I realized that CurrentRow is null,
        // doing impossible to change it to a previous one, this way avoiding an exception.
        if (this.Rows.Count > maxRowsAllowed)
        {
            this.Rows.RemoveAt(maxRowsAllowed);
        }
    }
}

Then, from a container class, inside AddRowAtBeginning method, a new row is inserted at 0 index, moving one index down the others.
When RowsAdded event is raised, and only if actual total rows count is greater than rowsAllowed the last is removed.

public class ContainerForm : Form
{
    private CustomDataGridView dgv;

    public ContainerForm()
    {
        InitializeComponent();

        dgv = new CustomDataGridView();

        dgv.Size = new Size(400, 200);
        dgv.Location = new Point(10, 10);
        this.Controls.Add(dgv);

        dgv.Start();
    }

    // Inserts a row at 0 index
    private void aButton_Click(object sender, EventArgs e)
    {
        var newRow = new DataGridViewRow();
        newRow.DefaultCellStyle.BackColor = Color.LightYellow;

        dgv.Rows.Insert(0, newRow);
    }
}

Everything is OK, until the CurrentRow (with the little arrow on header), due to displacement, is choosen to be removed.

I think, that's the reason an System.ArgumentOutOfRangeException is thrown, when RowsAdded escapes, tryng to return to dgv.Rows.Insert(0, newRow) line.

I could not find any solution yet.

1

There are 1 answers

1
Taksil On

try to change this

if (this.Rows.Count > maxRowsAllowed)
{
    this.Rows.RemoveAt(maxRowsAllowed);
}

to this

if (this.Rows.Count > maxRowsAllowed)
{
    // if the number of rows is 10
    // the index of the last item is 9
    // index 10 is out of range
    this.Rows.RemoveAt(maxRowsAllowed -1);
}