我正在使用c#上的窗口表单尝试使用openfile对话框打开文件时,当我浏览到我的文件并打开它时,打开的文件对话框会一直显示多次。
这是我打开文件的代码:
private void OpenBtn_Click(object sender, EventArgs e)
{
// Create OpenFileDialog
OpenFileDialog dlg = new OpenFileDialog();
// Set filter for file extension and default file extension
dlg.DefaultExt = ".xml";
dlg.Filter = "XML Files (*.xml)|*.xml";
// Display OpenFileDialog by calling ShowDialog method
DialogResult result = dlg.ShowDialog();
if (result == DialogResult.OK)
{
pathtext.Text = dlg.FileName;
sourceName = dlg.FileName;
}
// destFile = resultFile.Name;
if (pathtext.Text != null)
{
createBtn.Enabled = true;
}
}
和表单加载
中方法的此事件处理程序OpenBtn.Click += new EventHandler(this.OpenBtn_Click);
我无法看到我在哪里想念这件事。
答案 0 :(得分:0)
我可以重现您的错误的唯一方法是当我双击设计器中的按钮时,它会创建一个自动事件处理程序,您可以在事件属性中看到:
如果我除此之外还在代码中添加了事件With worksheets("sheet1")
If .AutoFilterMode Then .AutoFilterMode = False
With .Cells(1, "A").CurrentRegion
.AutoFilter Field:=2, Criteria1:=date
With .Resize(.Rows.Count - 1, .Columns.Count).Offset(1, 0)
If CBool(Application.Subtotal(103, .Cells)) Then
.specialcells(xlcelltypevisible).offset(0,1) = .parent.cells(13, "F").value2
End If
End With
End With
If .AutoFilterMode Then .AutoFilterMode = False
End With
的手动注册,例如在Click
事件中:
Load
然后我将得到对话框弹出两次的行为。如果我再一次这样做了:
private void Form1_Load(object sender, EventArgs e)
{
button2.Click += new EventHandler(this.OpenBtn_Click);
}
会弹出3次!您很可能在循环中注册此事件。因此,当第一个执行时,所有其他人都会跟进。删除手动注册行,并将事件处理程序名称简单地放入事件属性中。
编辑:主要问题是运营商private void Form1_Load(object sender, EventArgs e)
{
button2.Click += new EventHandler(this.OpenBtn_Click);
button2.Click += new EventHandler(this.OpenBtn_Click);
}
它将代理添加到内部列表中,如this answer中所述。