如何删除datagridview的行与删除按钮?按钮、datagridview

2023-09-03 05:59:03 作者:逆水寒

我有一个BindingSource的一个DataGridView绑定到一个DataTable。我已经把我的窗体上一个删除按钮,我想点击的时候它删除当前选中的行,像这样:

I've got a DataGridView with a BindingSource binding it to a DataTable. I've put a Delete button on my form and I want it to delete the currently selected row when clicked, something like this:

    if (dgvResourceSettings.CurrentRow != null && !dgvResourceSettings.CurrentRow.IsNewRow)
    {
        bindingSource.RemoveCurrent();
    }

的问题是,在新的行是在我的datagridview可见。如果用户选择该行,然后点击删除按钮则删除最后一个数据行,即上面的新建行之一。它这样做的原因是,当所述的datagridview失去焦点它当前行变更为最后一个数据行(如果当前行是新行)。我可以简单地切换出在DataGridView验证这一点。

The problem is that the New Row is visible on my datagridview. If the user selects that row and then clicks the Delete button then it deletes the last data row, ie the one above the New Row. The reason it does this is that when the datagridview loses focus it changes the current row to the last data row (if the current row was the New Row). I can verify this by simply tabbing off the datagridview.

所以我想对付这是正常的方式?我知道,用户可以只选择行和preSS DEL键,但我想给他们一个删除按钮也。

So I wonder what the normal way to deal with this is? I know users could just select the row and press the DEL key, but I want to give them a Delete button also.

感谢。

更新:从答案/评论看来,这种行为是正常的,所以很难有一个删除按钮,新建行。我选择删除新行,并有添加和删除按钮来代替。

UPDATE: From the answers/comments it seems that this behaviour is normal, so it's hard to have a Delete button and the New Row. I've opted to remove the New Row and have an Add and a Delete button instead.

推荐答案

源必须是这样的:当在DataGridView失去焦点是当前行更改为最后一个数据行。这是不正常的情况下,你必须做一些(KEYBD事件?)来做到这一点。

The source must be this: "when the datagridview loses focus it changes the current row to the last data row". This is not the normal case, you must be doing something (keybd events?) to make that happen.

我已经删除按钮下一个网格,他们工作得很好。

I have made delete buttons under a Grid and they worked fine.

编辑:澄清后,它是关于新建行的特殊地位,它是一种虚拟的。我有点看背后的推理,假设离开网格时选择没有转移回来。该CurrentRow将是空的。你的情况这将是美好的,但通常不会。

After clarification, it is about the special status of the 'New Row', it is kind of virtual. I sort of see the reasoning behind that, suppose the selection didn't shift back when leaving the Grid. The CurrentRow would be null. In your case that would be OK, but often it wouldn't.

一个想法:跟踪当前财产(的BindingSource),并禁止删除按钮,如果没有行是最新的。检查它的工作原理,当一个新的行(半)填补。

One idea: track the Current property (BindingSource) and disable the Delete button if no Row is current. Check how it works when a new row is (half) filled.

否则,杰夫的想法看起来不错。或者看到this问题。

And otherwise, Jeff's idea looks good too. Or see BFree's answer on this question.