[英]c# get control from another void/form (eventHandler)
在form1
我创建了一个名为formhaslo
简单表单。 我在创建formhaslo
称为控制listBoxhaslo
现在,我想创建MouseDoubleClick
事件到listBoxhaslo
。 我将listBoxhaslo
从formhaslo
移到form1
遇到问题。
您能看一下这段代码吗(请查看评论):
public partial class Form1 : Form
{
Form formhaslo = new Form();
...
...
...
public void buttonLoadPassForBAKFile_Click(object sender, EventArgs e)
{
int i = 0;
string path = @"Backups";
formhaslo.StartPosition = FormStartPosition.CenterScreen;
ListBox listBoxhaslo = new ListBox();
listBoxhaslo.Location = new System.Drawing.Point(0, 30);
listBoxhaslo.Left = (formhaslo.ClientSize.Width - listBoxhaslo.Width) / 2;
using (FileStream fsSbHaslo = new FileStream(path + @"\BAKPass._pass", FileMode.Open, FileAccess.Read, FileShare.Read))
{
using (StreamReader srhaslo = new StreamReader(fsSbHaslo, Encoding.Default))
{
string line;
while ((line = srhaslo.ReadLine()) != null)
{
listBoxhaslo.Items.Add(line);
i++;
}
srhaslo.Close();
}
formhaslo.Controls.Add(listBoxhaslo);
formhaslo.Controls.Add(label1);
listBoxhaslo.MouseDoubleClick += new MouseEventHandler(listBoxhaslo_MouseDoubleClick); // <---here is EventHandler
formhaslo.Show();
}
}
void listBoxhaslo_MouseDoubleClick(object sender, MouseEventArgs e)
{
if ((listBoxhaslo.SelectedItem) != null) // <--listBoxhaslo does not exist in current context
{
PassForBakFile = (listBoxhaslo.SelectedItem.ToString());
formhaslo.Hide();
}
}
我知道此错误一定存在,因为我做错了,但我不知道该怎么做。
listBoxhaslo不存在,因为它是在事件listBoxhaslo_MouseDoubleClick的第二个函数不可见的第一个函数的范围内声明的。 为了使它起作用,您需要在函数外部声明listBoxhaslo变量。 您可以在formhaslo附近顶部之后声明它。 或完成此操作的另一种方法是将发件人转换为事件中的ListBox。
void listBoxhaslo_MouseDoubleClick(object sender, MouseEventArgs e)
{
var listBoxhaslo = (sender as ListBox);
if (listBoxhaslo.SelectedItem != null)
{
PassForBakFile = (listBoxhaslo.SelectedItem.ToString());
formhaslo.Hide();
}
}
我没有尝试过该代码,但我认为它可以。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.