首页 > 解决方案 > 从 datagridview 复制到剪贴板

问题描述

有谁知道为什么下面的代码是通过单击按钮从 datagridview 中复制选定的单元格值,而当我在自定义 contextMenuStrip 下使用此部分时它不起作用?最奇怪的是,当我复制一个复选框单元格时,它正在工作,当你粘贴这个值时,你会得到“真”

请参阅 GIF 图像。C

按钮点击:

private void button1_Click(object sender, EventArgs e)
{
  if (dataGridView1.GetCellCount(DataGridViewElementStates.Selected) > 0)
  {
    try
    {
      // Add the selection to the clipboard.
      Clipboard.SetDataObject(
      dataGridView1.GetClipboardContent());
    }
    catch (System.Runtime.InteropServices.ExternalException)
    {
       //..
    }
  }
}

上下文菜单条:

private void cutctrlXToolStripMenuItem_Click(object sender, EventArgs e)
{
  if (dataGridView1.GetCellCount(DataGridViewElementStates.Selected) > 0)
  {
    try
    {
      // Add the selection to the clipboard.
      Clipboard.SetDataObject(
      dataGridView1.GetClipboardContent());
    }
    catch (System.Runtime.InteropServices.ExternalException)
    {
       //..
    }

    foreach (DataGridViewCell dgvCell in dataGridView1.SelectedCells)
    {
      dgvCell.Value = string.Empty;
    }
  }
}

标签: c#

解决方案


我想到了。正是因为这条线通过第一次单击(而不是两次)激活了数据网格中的组合框

dataGridView1.EditMode = DataGridViewEditMode.EditOnEnter;

删除此部分时,它正在工作。为了解决组合框的第一次点击,我添加了这部分:

private void datagridview_CellEnter(object sender, DataGridViewCellEventArgs e)
{
    bool validClick = (e.RowIndex != -1 && e.ColumnIndex != -1); //Make sure the clicked row/column is valid.
    var datagridview = sender as DataGridView;

    // Check to make sure the cell clicked is the cell containing the combobox 
    if(datagridview.Columns[e.ColumnIndex] is DataGridViewComboBoxColumn && validClick)
    {
        datagridview.BeginEdit(true);
        ((ComboBox)datagridview.EditingControl).DroppedDown = true;
    }
}

推荐阅读