使用 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 索引处插入一个新行,将一个索引向下移动其他索引。引发事件时,并且仅
当实际总行数大于最后一个时才会被删除。 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
(标题上有小箭头)由于位移而被选择删除。
我认为,这就是 anSystem.ArgumentOutOfRangeException
被抛出的原因,当RowsAdded
逃跑时,试图返回dgv.Rows.Insert(0, newRow)
线。
我还没有找到任何解决方案。