如何防止从绑定到DataGridView的DataTable中删除最后一个DataRow时出错
本文关键字:删除 最后一个 DataRow 出错 DataTable 何防止 绑定 DataGridView | 更新日期: 2023-09-27 18:24:30
在我的WinForms应用程序中,按下按钮会触发以下逻辑:
private void ExecuteSelectedConsoleCommand()
{
var commandsRow = GetCommandsRow();
var consoleCommand = GetConsoleCommand(commandsRow);
Task.Factory.StartNew(() =>
{
var runningCommandRow =
runtimeDataSet.RunningCommands.AddRunningCommandsRow(Guid.NewGuid(),
consoleCommand.OneLineDescription);
consoleCommand.Run(null);
runningCommandRow.Delete();
});
}
BindingSource用于让DataGridView自动更新自身。
到目前为止,如果没有下面的破解,我会收到一个错误,说"索引0无效"。
// prevents error when removing last row from data bound datagridview
var placeholder = runtimeDataSet
.RunningCommands
.AddRunningCommandsRow(Guid.NewGuid(), "PLACEHOLDER");
有了上面的代码,DataGridView中总是至少有一行,它就可以正常工作了。
我该如何解决这个问题?
注意:这似乎是许多其他人都会遇到的情况,但我的网络搜索失败了。。
我也遇到过同样的问题。经过一番尝试和错误之后,我发现你必须处理datagridview的几个事件才能消除这种情况,即使这样也需要一些错误忽略。我不记得我到底做了什么来避免这个错误,但我认为以下片段可能会提供一些见解(评论中的解释):
删除行:
//When I remove a row that has been added, but not commited return from the function
//run the update function only if the row is commited (databound)
private void dgvTest_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e) {
if (_lastDataRow == null || _lastDataRow.RowState == DataRowState.Added)
return;
UpdateRowToDatabase();
}
行验证:
//I got the kind of Index not valid or other index errors
//RowValidating is fired when entering the row and when leaving it
//In my case there was no point in validating on row enter
private void dgvTest_RowValidating(object sender, DataGridViewCellCancelEventArgs e) {
if (Disposing)
return;
if (!dgvTest.IsCurrentRowDirty) {
return;
}
try {
var v = dgvTest.Rows[e.RowIndex].DataBoundItem;
} catch {
return;
}
}
数据错误:
//I had to trap some errors and change things accordingly
private void dgvTest_DataError(object sender, DataGridViewDataErrorEventArgs e) {
if (e.Exception.Message.Contains("Index") && e.Exception.Message.Contains("does not have a value")) {
//when editing a new row, after first one it throws an error
//cancel everything and reset to allow the user to make the desired changes
bindingSource.CancelEdit();
bindingSource.EndEdit();
bindingSource.AllowNew = false;
bindingSource.AllowNew = true;
e.Cancel = true;
dgvTest.Visible = false;
dgvTest.Visible = true;
}
}
行输入:
//Some problemes occured when entering a new row
//This resets the bindingsource's AllowNew property so the user may input new data
private void dgvTest_RowEnter(object sender, DataGridViewCellEventArgs e) {
if (!_loaded)
return;
if (e.RowIndex == dgvTest.NewRowIndex)
if (String.IsNullOrWhiteSpace(dgvTest.Rows[e.RowIndex == 0 ? e.RowIndex : e.RowIndex - 1].Cells[_idColumn].Value.ToStringSafe())) {
bindingSource.CancelEdit();
bindingSource.AllowNew = false;
bindingSource.AllowNew = true;
}
}
希望这能有所帮助!