有人可以建议如何做到这一点吗?
目前我有:
- 具有四列的 DataGridView - Text1 |文本2 |编辑按钮 |保存按钮
- 当我点击 Text1 时,它变成一个可编辑字段,我可以 改变它的值
- 然后我尝试编辑 Text2,但单击此单元格会保存我在 Text1 中的更改
问题是:当我尝试编辑第二个字段(Text2)时,第一个字段(Text1)失去焦点,退出编辑模式并保存我同时所做的更改,我想保存所有更改同时连续。
我想实现什么:
- 我按下编辑按钮,所有单元格都变为可编辑状态,这样我就可以更改一行中任何单元格的值
- 我更改 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);
}
}
}
关于c# - 编辑 DataGridView 中的整行(不仅仅是一个单元格),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18345079/