1

这真的很奇怪,由于某种原因,我的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);

        }
    }
}

}
4

2 回答 2

4

它应该在您的窗口的构造函数中:

public MyWindow()
{

//here inicialization

contexMenuuu.ItemClicked +=
new ToolStripItemClickedEventHandler(contexMenuuu_ItemClickedd);
}

这是一个非常常见的错误,多次添加事件处理程序,下次要小心

于 2012-11-16T18:04:21.823 回答
1

就我而言,我已经使用以下语句解决了它 -

e.Handled = true;

这会将事件标记为已处理(显然)。

于 2015-06-08T10:04:56.617 回答