有人知道为什么下面的代码通过单击鼠标右键从datagridview复制选定的单元格值,而当我在自定义contextMenuStrip下使用此部件时,它不起作用吗?最奇怪的是,当我复制一个复选框单元格时,它可以正常工作,当您粘贴此值时,您会得到“ true”
按钮单击:
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)
{
//..
}
}
}
ContextMenuStrip:
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;
}
}
}
答案 0 :(得分:1)
我知道了。正是由于这一行,才通过第一次单击(而不是两次)激活了数据网格中的组合框
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;
}
}