[英]ContextMenu Click Event firing more than once
This is really strange, for some reason my contextmenu
clicks are firing more than once. 这真的很奇怪,由于某种原因,我的contextmenu
点击多次触发。 I have the contextmenu tied to a button, so when the button is clicked the contextmenu
is shown under it (with more options). 我将contextmenu绑定到一个按钮,因此单击该按钮时, contextmenu
显示在其下方(带有更多选项)。
One option is to save listview
to Excel, the other is to save to .csv. 一种选择是将listview
保存到Excel,另一种是保存到.csv。
So basically what happens here is that multiple excel sheets will open. 因此,基本上这里发生的是将打开多个Excel工作表。 Of course I only want one excel to open :) 当然,我只想要一个excel打开:)
Here is my code: 这是我的代码:
private void toolButtonNoBorder3_Click(object sender, EventArgs e)
{
contexMenuuu.Show(toolButtonNoBorder3,
new Point(0, toolButtonNoBorder3.Height));
contexMenuuu.ItemClicked +=
new ToolStripItemClickedEventHandler(contexMenuuu_ItemClickedd);
}
void contexMenuuu_ItemClickedd(object sender, ToolStripItemClickedEventArgs e)
{
contexMenuuu.Hide();
contexMenuuu.Close();
if (e.ClickedItem.Text == "Excel")
{
Microsoft.Office.Interop.Excel.Application app =
new Microsoft.Office.Interop.Excel.Application();
app.Visible = true;
Microsoft.Office.Interop.Excel.Workbook wb = app.Workbooks.Add(1);
Microsoft.Office.Interop.Excel.Worksheet ws =
(Microsoft.Office.Interop.Excel.Worksheet)wb.Worksheets[1];
int i = 1;
int i2 = 1;
int iad = 1;
foreach (ListViewItem lvi in flatListView1.Items)
{
i = 1;
foreach (ListViewItem.ListViewSubItem lvs in lvi.SubItems)
{
if (i2 == 1)
{
iad = 1;
foreach (ColumnHeader lvfi in flatListView1.Columns)
{
try
{
ws.Cells[i2, iad] = lvfi.Text;
}
catch (Exception ee)
{
}
iad++;
}
}
else
{
try
{
ws.Cells[i2, i] = lvs.Text;
}
catch (Exception ee)
{
}
}
i++;
}
i2++;
}
}
else if (e.ClickedItem.Text == "CSV")
{
Stream myStream;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "csv files (*.csv)|*.csv";
saveFileDialog1.FilterIndex = 2;
saveFileDialog1.RestoreDirectory = true;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if ((myStream = saveFileDialog1.OpenFile()) != null)
{
myStream.Close();
ListViewToCSV(flatListView1, saveFileDialog1.FileName, true);
}
}
}
}
It should be in a constructor of your window: 它应该在窗口的构造函数中:
public MyWindow()
{
//here inicialization
contexMenuuu.ItemClicked +=
new ToolStripItemClickedEventHandler(contexMenuuu_ItemClickedd);
}
This is a very common error to add event handler more than once, be careful next time 多次添加事件处理程序是一个非常常见的错误,下次请小心
In my case I have solved it using following statement - 就我而言,我已经使用以下语句解决了它-
e.Handled = true;
This will mark the event as handled (Obviously). 这会将事件标记为已处理(很明显)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.