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 インデックスに挿入され、1 つのインデックスが他のインデックスの下に移動します。イベントが発生し、実際の合計行数が前回 よりも多い場合
のみ削除されます。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(ヘッダーに小さな矢印が付いている) が変位により削除される まで、すべて問題ありません。

それが、逃げるときにラインに戻ろうとしてSystem.ArgumentOutOfRangeException投げられる理由だと思います。 RowsAddeddgv.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 に答える