c# - 从 datagridview 复制到剪贴板
问题描述
有谁知道为什么下面的代码是通过单击按钮从 datagridview 中复制选定的单元格值,而当我在自定义 contextMenuStrip 下使用此部分时它不起作用?最奇怪的是,当我复制一个复选框单元格时,它正在工作,当你粘贴这个值时,你会得到“真”
按钮点击:
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;
}
}
}
解决方案
我想到了。正是因为这条线通过第一次单击(而不是两次)激活了数据网格中的组合框
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;
}
}
推荐阅读
- django - Celery/Django 在设置时区时每毫秒运行一次任务,而不是按计划运行
- php - PHP警告无法打开流:没有这样的文件或目录
- elf - 在 GRUB 的源代码中哪里可以找到 ELF 内核加载程序?
- proxy - 电子代理
- java - 如何打开jfr部分文件
- java - 如何在java中通过用户定义的名称获取枚举?
- ios - 可选链接的 EXC_BREAKPOINT
- sql-server - SQL Server 条件 CASE JOIN 查询
- java - Android Room:如何使用嵌入的自定义查询
- android - ListView 未从异步刷新(布局可能存在问题)