如何在开头插入新数据网格视图行时删除最后一个数据网格视图行

本文关键字:视图 网格 数据 删除 最后一个 数据网 开头 新数据 插入 | 更新日期: 2023-09-27 18:31:38

使用 Windows 窗体应用程序。
我有这个类,派生自一个DataGridView控件:

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);
        }
    }
}

然后,从容器类中,在方法AddRowAtBeginning 索引处插入一个新行,将一个索引向下移动其他索引。
引发RowsAdded事件时,仅当实际总行数大于rowsAllowed时,才会删除最后一个行数。

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);
    }
}

一切正常,直到由于位移而选择删除CurrentRow(标题上有小箭头)。

我想,这就是System.ArgumentOutOfRangeException被扔的原因,当RowsAdded逃跑时,试图回到dgv.Rows.Insert(0, newRow)线。

我还找不到任何解决方案。

如何在开头插入新数据网格视图行时删除最后一个数据网格视图行

尝试更改此设置

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

对此

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);
}