What if you tried removing those UseColumnTextForButtonValue
statements and initialized whenever a new row is added?
private void InitializeParentGrid()
{
parentGrid = new DataGridView
{
Dock = DockStyle.Fill,
AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill,
RowHeadersVisible = false,
AllowUserToAddRows = false,
ColumnHeadersVisible = false // Hide column headers
};
var expandColumn = new DataGridViewButtonColumn
{
Name = "Expand",
HeaderText = "",
Width = 30, // Set a small width
AutoSizeMode = DataGridViewAutoSizeColumnMode.None,
};
parentGrid.Columns.Add(expandColumn);
var yearColumn = new DataGridViewTextBoxColumn
{
Name = "Year",
HeaderText = "Year",
DataPropertyName = "Year"
};
parentGrid.Columns.Add(yearColumn);
groupBox1.Controls.Add(parentGrid);
parentGrid.CellContentClick += ParentGrid_CellContentClick;
parentGrid.RowsAdded += (sender, e) =>
{
var exp = parentGrid.Columns["Expand"].Index;
if (parentGrid.Rows[e.RowIndex].Cells[exp] is DataGridViewButtonCell button)
{
button.Value = "▶";
}
};
parentGrid.Rows.Add();
parentGrid.Rows.Add();
parentGrid.Rows.Add();
}
private void ParentGrid_CellContentClick(object? sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex == -1 && e.ColumnIndex == -1 ) return;
if (parentGrid?[e.ColumnIndex, e.RowIndex] is DataGridViewButtonCell button)
{
button.Value =
Equals(button.Value, "▶")
? "▽"
: "▶";
}
}