编辑DataGridView中的整行(而不仅仅是一个单元格)
本文关键字:DataGridView 一个 单元格 不仅仅是 编辑 | 更新日期: 2023-09-27 18:28:27
有人能建议如何做到这一点吗?
目前我有:
- 具有四列的DataGridView-Text1|Text2|EditButton | SaveButton
- 当我点击Text1时,它变成了一个可编辑的字段,我可以更改其值
- 然后我尝试编辑Text2,但点击这个单元格会将我的更改保存在Text1中
问题是:当我试图编辑第二个字段(Text2)时,第一个字段(Text1)失去焦点,退出编辑模式并保存我同时所做的更改,我想同时将所有更改保存在一行中。
我想要实现的:
- 我按下EditButton,所有单元格都可以编辑,这样我就可以更改一行中任何单元格的值
- 我更改Text1的值,然后更改Text2的值
- 只有当我按下SaveButton时,它才会保存所做的更改
问题是:如何保持一行中的所有单元格处于编辑模式,直到我按下特定按钮?
也许你可以使用像这样的自定义DataGridView
public class CustomDGV : DataGridView
{
private object _cellValue;
private Dictionary<int, object[]> _pendingChanges;
public CustomDGV()
{
_pendingChanges = new Dictionary<int, object[]>();
}
protected override void OnCellBeginEdit(DataGridViewCellCancelEventArgs e)
{
// Save the value of the cell before edit
_cellValue = this[e.ColumnIndex, e.RowIndex].Value;
// If there's already a pending change for that cell, display the edited value
if (_pendingChanges.ContainsKey(e.RowIndex))
{
this[e.ColumnIndex, e.RowIndex].Value = _pendingChanges[e.RowIndex][e.ColumnIndex];
}
base.OnCellBeginEdit(e);
}
protected override void OnCellEndEdit(DataGridViewCellEventArgs e)
{
// Adds the edited value of the cell into a dictionary
if (!_pendingChanges.ContainsKey(e.RowIndex))
{
_pendingChanges.Add(e.RowIndex, new object[this.ColumnCount]);
}
_pendingChanges[e.RowIndex][e.ColumnIndex] = this[e.ColumnIndex, e.RowIndex].Value;
// Display the "old" value
this[e.ColumnIndex, e.RowIndex].Value = _cellValue;
}
public void SavePendingChanges(int rowIndex)
{
if (_pendingChanges.ContainsKey(rowIndex))
{
// Gets the pending changes for that row
var rowData = _pendingChanges[rowIndex];
// Update every cell that's been edited
for(int i = 0; i < rowData.Length; i++)
{
if (rowData[i] != null)
this[i, rowIndex].Value = rowData[i];
}
// Removes the pending changes from the dictionary once it's saved
_pendingChanges.Remove(rowIndex);
}
}
}
在CellContentClick上,您可以调用SavePendingChanges()
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex > -1 && e.RowIndex > -1)
{
if (e.ColumnIndex == 3) // Save button
{
dataGridView1.SavePendingChanges(e.RowIndex);
}
}
}
好的,我知道它看起来可能有点乱,但这似乎是我能想到的最简单的解决方案-当网格进入编辑模式时,在每个只读单元格上显示TextBox:
public void DisplayEditors(DataGridView grid, DataGridViewRow row)
{
foreach (DataGridViewCell cell in row.Cells)
{
if (cell.ReadOnly == false)
{
var place = grid.GetCellDisplayRectangle(cell.ColumnIndex, cell.RowIndex, true);
var name = string.Format("EDITOR-{0}-{1}", cell.ColumnIndex, cell.RowIndex);
var editor = grid.Controls.Find(name, false).FirstOrDefault();
if (editor == null)
{
editor = new TextBox();
(editor as TextBox).Name = name;
grid.Controls.Add(editor);
}
else
{
editor.Show();
}
editor.Size = place.Size;
editor.Location = place.Location;
editor.Text = Convert.ToString(cell.Value);
}
}
}