Using a Windows Forms application.
I have this class, derived from a DataGridView
control:
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);
}
}
}
Then, from a container class, inside AddRowAtBeginning
method, a new row is inserted at 0 index, moving one index down the others.
When RowsAdded
event is raised, and only if actual total rows count is greater than rowsAllowed
the last is removed.
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);
}
}
Everything is OK, until the CurrentRow
(with the little arrow on header), due to displacement, is choosen to be removed.
I think, that's the reason an System.ArgumentOutOfRangeException
is thrown, when RowsAdded
escapes, tryng to return to dgv.Rows.Insert(0, newRow)
line.
I could not find any solution yet.
try to change this
to this