我通过代码创建了一个 gridview,当用户单击该按钮时,我想将单击行的按钮文本从 + 更改为 -。我检查了下面的多个代码,我正在使用的代码正在尝试将文本从 + 更改为 - ,反之亦然ParentGrid_CellContentClick
private void InitializeParentGrid()
{
parentGrid = new DataGridView
{
Dock = DockStyle.Fill,
AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill,
RowHeadersVisible = false,
AllowUserToAddRows = false,
ColumnHeadersVisible = false // Hide column headers
};
// Add Expand button column
var expandColumn = new DataGridViewButtonColumn
{
Name = "Expand",
HeaderText = "",
Text = "+",
UseColumnTextForButtonValue = true,
Width = 30, // Set a small width
AutoSizeMode = DataGridViewAutoSizeColumnMode.None,
};
expandColumn.UseColumnTextForButtonValue = true;
parentGrid.Columns.Add(expandColumn);
// Add Year column
var yearColumn = new DataGridViewTextBoxColumn
{
Name = "Year",
HeaderText = "Year",
DataPropertyName = "Year"
};
parentGrid.Columns.Add(yearColumn);
// Add Parent Grid to GroupBox1
groupBox1.Controls.Add(parentGrid);
// Parent grid events
parentGrid.CellContentClick += ParentGrid_CellContentClick;
}
在这里,我在单击后将网格单元格值 + 更改为 -
private void ParentGrid_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex < 0) return;
if (e.ColumnIndex == 0)
{
var buttonCell = (DataGridViewButtonCell)parentGrid.Rows[e.RowIndex].Cells[0];
if (expandedRowIndex == e.RowIndex)
{
// Collapse if already expanded
RemoveChildGrid();
expandedRowIndex = -1;
// Change the button text back to "+"
buttonCell.Value = "+"; // Change button text for the clicked row
}
else
{
// Collapse any existing child grid first
RemoveChildGrid();
// Expand new child grid
expandedRowIndex = e.RowIndex;
AddChildGrid(e.RowIndex);
// Change the button text to "-"
buttonCell.Value = "-"; // Change button text for the clicked row
}
// Force the DataGridView to redraw this specific cell
parentGrid.InvalidateCell(buttonCell);
}
}
如果您尝试删除这些
UseColumnTextForButtonValue
语句并在添加新行时进行初始化,结果会怎样?