[英]C# DataGridView edit cell value
全部。 我已经用谷歌搜索这个问题一个小时了,但仍然无法理解它是如何工作的。 我的表单上有 DataGridView 控件,它有 3 列 + 1 ButtonColumn,我向其中添加了如下几行:
dg.Rows.Add(param1, param2, param3);
按钮的文本设置如下:
DataGridViewButtonColumn bc = (DataGridViewButtonColumn)dg.Columns["ButtonColumn"];
bc.Text = "Action";
bc.UseColumnTextForButtonValue = true;
现在,我想更改特定按钮的文本,一旦用户点击它,让我们说“完成”。 我是这样试的:
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) {
if (articles.Rows[e.RowIndex].Cells[e.ColumnIndex].GetType() == typeof(DataGridViewButtonCell)) {
DataGridViewButtonCell cell = (DataGridViewButtonCell)articles.Rows[e.RowIndex].Cells[e.ColumnIndex];
articles.CurrentCell = cell;
articles.EditMode = DataGridViewEditMode.EditProgrammatically;
articles.BeginEdit(false);
cell.Value = "Done";
articles.EndEdit();
}
}
它不起作用。 我在 stackoverflow 上尝试了一些类似问题的答案,但效果不佳。 如果我忽略了什么,请原谅我。 有没有人会这么好心地向我解释如何做到这一点,为什么这不起作用?
更新:
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) {
if (articles.Rows[e.RowIndex].Cells[e.ColumnIndex].GetType() == typeof(DataGridViewButtonCell)) {
articles.EditMode = DataGridViewEditMode.EditProgrammatically;
articles.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = "Done";
}
}
更新2:
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) {
if (articles.Rows[e.RowIndex].Cells[e.ColumnIndex].GetType() == typeof(DataGridViewButtonCell)) {
articles.EditMode = DataGridViewEditMode.EditProgrammatically;
articles.ReadOnly = false;
articles.Rows[e.RowIndex].ReadOnly = false;
articles.Rows[e.RowIndex].Cells[e.ColumnIndex].ReadOnly = false;
articles.CurrentCell = articles.Rows[e.RowIndex].Cells[e.ColumnIndex];
articles.BeginEdit(true);
if (articles.Rows[e.RowIndex].Cells[e.ColumnIndex].IsInEditMode) { //it's false here
articles.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = "Done";
}
articles.EndEdit();
}
}
我什至无法在调试器中手动更改值,它会立即设置回旧值。 该问题似乎与 DataGridViewButtonCell 相关,因为其他类型的单元格变化良好。
您需要从使用 cell.Value 更改为
articles.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = "Done";
更改单元格值仅在您将该单元格添加回 datagridview 时才会更改。 通过这种方式,您可以摆脱像这样使用单元格。
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) {
if (articles.Columns[e.ColumnIndex].GetType() == typeof(DataGridViewButtonColumn)) {
articles.EditMode = DataGridViewEditMode.EditProgrammatically;
articles.Rows[e.RowIndex].Cells[e.ColumnIndex].ReadOnly = false;
articles.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = "Done";
}
}
我编辑了其余部分,因为我认为您正在做的事情不需要它。
问题出在这行代码中:
bc.UseColumnTextForButtonValue = true;
设置后,将无法编辑 ButtonCell 的值。 DataGridView 的任何只读选项在这里都无关紧要,它们指定用户(而不是您)是否可以编辑单元格。
感谢您的帮助,@deathismyfriend
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.