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 つのインデックスが他のインデックスの下に移動します。イベントが発生し、実際の合計行数が前回 よりも多い場合
にのみ削除されます。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)
私はまだ解決策を見つけることができませんでした。