【问题标题】:c# get control from another void/form (eventHandler)c# 从另一个 void/form (eventHandler) 获取控制权
【发布时间】:2015-07-19 06:21:15
【问题描述】:

form1 中,我创建了名为formhaslo 的简单表单。 我在formhaslo 中创建了名为listBoxhaslo 的控件 现在,我想为listBoxhaslo 创建MouseDoubleClick 事件。 我无法将listBoxhasloformhaslo 转换为form1

你能看一下这段代码吗(请查看 cmets):

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

我知道这个错误一定存在,因为我做错了,但我不知道该怎么做。

【问题讨论】:

    标签: c# forms controls eventhandler


    【解决方案1】:

    listBoxhaslo 不存在,因为它是在第一个函数的范围内声明的,这对事件 listBoxhaslo_MouseDoubleClick 的第二个函数不可见。为了使其工作,您需要在函数之外声明 listBoxhaslo 变量。您可以在靠近顶部的 formhaslo 之后声明它。或者另一种方法是在您的事件中将 sender 强制转换为 ListBox。

    void listBoxhaslo_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            var listBoxhaslo = (sender as ListBox);
    
            if (listBoxhaslo.SelectedItem != null) 
            {
                PassForBakFile = (listBoxhaslo.SelectedItem.ToString());
                formhaslo.Hide();
            }
        }
    

    我还没有尝试过代码,但我认为它可以。

    【讨论】:

    • 这就是我要找的。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-28
    • 2020-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-08
    • 2012-06-08
    相关资源
    最近更新 更多