contextMenuStrip 控件,高手指點?
本人在contextMenuStrip控件裡添加了三個Item,復制,粘貼,剪切,然後和datagridview幫定,當我選中datagridview中的單元格後右擊單元格後出現這三個Item,當我點復制後,要復制此單元格中的內容再粘貼到下一條記錄中的單元格。就像是在EXCEL中操作數據一樣。
請問在點復制時這個CLICK事件怎麼寫?後面的粘貼和剪切一樣怎麼寫呢?
------解决方案--------------------ContextMenuStrip context = new ContextMenuStrip();
ToolStripMenuItem tool = new ToolStripMenuItem();
tool.Text = "Copy ";
context.Items.AddRange(new ToolStripMenuItem[]{ tool });
tool.Click += new EventHandler(tool_Click);
void tool_Click(object sender, EventArgs e)
{
//do copy
}
------解决方案--------------------难倒是不难,就是繁琐,本来只想给你说下思路的,不过因为自己没做过,所以做了下测试,既然代码都写了,那就给你贴出来吧
注意下SelectionMode属性应为CellSelect
private void btnCopy_Click(object sender, EventArgs e) //复制
{
if (dataGridView3.CurrentCell.RowIndex != -1)
{
string value = dataGridView3.CurrentCell.Value.ToString();
Clipboard.SetData(DataFormats.Text, value);
}
}
private void btnCut_Click(object sender, EventArgs e) //剪切
{
if (dataGridView3.CurrentCell.RowIndex != -1)
{
dataGridView3.CurrentCell.Value = Clipboard.GetData(DataFormats.Text).ToString();
}
}
private void btnPaste_Click(object sender, EventArgs e) //粘贴
{
if (dataGridView3.CurrentCell.RowIndex != -1)
{
dataGridView3.CurrentCell.Value = Clipboard.GetData(DataFormats.Text).ToString();
}
}
private void dataGridView3_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.RowIndex != -1 && e.ColumnIndex != -1)
{
for (int i = 0; i < dataGridView3.SelectedCells.Count; i++)
{
dataGridView3.SelectedCells[i].Selected = false;
}
dataGridView3.Rows[e.RowIndex].Cells[e.ColumnIndex].Selected = true;
dataGridView3.CurrentCell = dataGridView3.Rows[e.RowIndex].Cells[e.ColumnIndex];
}
}
不过还有个在RowHeaders上弹出右键的问题,懒得写代码了,你自己解决一下吧
另外就是有些代码没有优化,自己看下