2015-07-19 13 views
0

form1我创建了一个简单的表格formhaslo。 我在formhaslo控件中创建了listBoxhaslo 现在,我想创建MouseDoubleClick事件到listBoxhaslo。 我有listBoxhasloformhasloform1的问题。c#从另一个void/form获取控件(eventHandler)

你可以看看这个代码,请(请查看评论):

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();  
     } 
} 

我知道,这个错误必须在那里,因为即时通讯做是错误的,但我不知道该怎么做。

回答

0

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(); 
     } 
    } 

我还没有尝试过代码,但我认为它会做。

+0

这就是我一直在寻找的东西。谢谢 – Kafus

+0

很高兴帮助你:) – jtabuloc

相关问题