這是很奇怪的,由於某種原因,我contextmenu
點擊次數射擊不止一次。我有文本菜單綁在按鈕,這樣當點擊按鈕時contextmenu
下它示出(有更多的選項)。文本菜單點擊事件觸發不止一次
一種選擇是保存listview
到Excel,另一種是保存爲.csv。
所以基本上在這裏發生的事情是,多個Excel工作表將打開。當然,我只想要一個Excel打開:)
這裏是我的代碼:
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);
}
}
}
}
是,當您訂閱的Click事件不止一次發生。就像你在你的代碼中一樣。每次用戶單擊toolButtonNoBorder3按鈕時,都會向同一個Click事件添加另一個事件處理程序。該代碼屬於構造函數,因此只能執行一次。 –
我該如何解決這個問題? – Jacqueline
Quote:'代碼屬於構造函數' –