从绑定到DataGridView的DataTable中删除最后一个DataRow时如何防止错误?

时间:2013-07-24 04:24:07

标签: c# .net winforms datagridview

在我的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中始终至少有一行,它可以正常工作。

我该如何解决这个问题?

注意:这似乎是许多其他人会遇到的问题,但我的网络搜索失败了..

1 个答案:

答案 0 :(得分:1)

我遇到了同样的问题。经过一些试验和错误后,我发现你必须处理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;
                }
        }

希望这有帮助!