简体   繁体   English

Ctrl + x剪切操作不适用于DataGridView

[英]Ctrl+x cut operation Doesn't works on DataGridView

I have bound a DataTable with the DataGridView as in the below image. 我已经将DataTableDataGridView绑定在一起,如下图所示。

的DataGridView

I need to select multiple cells and perform a cut operation by pressing ctrl + x on the keyboard, but I can't get this to work. 我需要选择多个单元格并通过按键盘上的ctrl + x来执行剪切操作,但是我无法执行此操作。

Does anyone know how to achieve this? 有谁知道如何实现这一目标?

What you need to do when your application receives a "cut" (cntrl-X) command is to copy the selected cells to the clipboard. 当应用程序收到“剪切”(cntrl-X)命令时,您需要做的就是将选定的单元格复制到剪贴板。 You then need to remove those cells from the datagrid pragmatically by first updating your database (delete/remove the 'cut' data), and then refreshing your datagridview to reflect the change. 然后,您需要通过首先更新数据库(删除/删除“剪切”数据),然后刷新datagridview以反映更改,从实用的角度将这些单元格从datagrid删除。

Note: it is up to your design if you want to wait to actually commit the data change until the data is no longer in the clipboard because if you make all the changes permanent, it will be harder to perform a potential 'undo'. 注意:如果要等待实际提交数据更改直到数据不再存在于剪贴板中,则取决于您的设计,因为如果将所有更改永久化,则执行潜在的“撤消”操作将更加困难。

To copy the selected cells your code should look something like this: 要复制选定的单元格,您的代码应如下所示:

private void CopyPasteButton_Click(object sender, System.EventArgs e)
{
    if (this.DataGridView1
        .GetCellCount(DataGridViewElementStates.Selected) > 0)
{
    try
    {
        // Add the selection to the clipboard.
        Clipboard.SetDataObject(
            this.DataGridView1.GetClipboardContent());

        // Replace the text box contents with the clipboard text.
        this.TextBox1.Text = Clipboard.GetText();
    }
    catch (System.Runtime.InteropServices.ExternalException)
    {
        this.TextBox1.Text = 
            "The Clipboard could not be accessed. Please try again.";
    }
}

I see a potential problem that you may need to address. 我看到您可能需要解决的潜在问题。 In your picture you are only selecting some of the columns of your data grid view. 在图片中,您仅选择数据网格视图的某些列。 If this view represents an entire database table, you may want the user to select an entire row instead of a partial row. 如果此视图表示整个数据库表,则可能希望用户选择整个行而不是部分行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM