簡體   English   中英

C# DataGridView 編輯單元格值

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM