C#DataGridView编辑单元格值

问题描述 投票:0回答:2

所有。我一直在谷歌搜索这个问题一个小时,仍然无法理解它是如何工作的。我的表单上有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";
    }
}

UPDATE2:

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特别明显,因为其他类型的单元格变化很好。

c# winforms datagridview
2个回答
0
投票

你需要从使用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";
    }
}

我把剩下的编辑了,因为我不相信你正在做的事情需要它。


0
投票

问题出在这行代码中:

bc.UseColumnTextForButtonValue = true;

设置后,无法编辑ButtonCell的值。 DataGridView的任何只读选项都与此无关,它们指定用户(而不是您)是否可以编辑单元格。

谢谢你的帮助,@ deathismyfriend

© www.soinside.com 2019 - 2024. All rights reserved.