1

使用 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方法中,在 0 索引处插入一个新行,将一个索引向下移动其他索引。引发事件时,并且
当实际总行数大于最后一个时才会被删除。 RowsAddedrowsAllowed

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(标题上有小箭头)由于位移而被选择删除。

我认为,这就是 anSystem.ArgumentOutOfRangeException被抛出的原因,当RowsAdded逃跑时,试图返回dgv.Rows.Insert(0, newRow)线。

我还没有找到任何解决方案。

4

1 回答 1

0

尝试改变这一点

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);
}
于 2014-11-25T04:00:26.223 回答