0

我有 Form1 和 Form1.cs 文件,它调用 Helpers.cs 中的方法。此方法将导致表单的实例作为参数,然后创建一个按钮和文本框,并为按钮分配一个处理程序。当按钮处理程序启动时如何将文本框文本值传输到处理程序方法?Helpers.cs 有这个方法:

       public static void startpage(Form form)
    {
        try
        {
            var Tip = new Label() { Text = "Input instance name",
                Location = new Point(50, 50), AutoSize = true };

            var StartConnection = new LinkLabel() { Text = "Connect", 
                Location = new Point(50, 100), AutoSize = true};

            var InstanceInput = new TextBox() { Text = "INSTANCENAME", 
                Location = new Point(100, 70), MaxLength = 1000, Width = 200,
            BorderStyle=BorderStyle.FixedSingle};

            StartConnection.Click += new EventHandler(nextpage);

            Helpers.AddControlsOnForm(form,
                new Control[] {Tip,StartConnection,InstanceInput });

        }
        catch(Exception ex) 
        { MessageBox.Show("Error occured. {0}",ex.Message.ToString()); }
    }
      public static void nextpage(Object sender, EventArgs e)
    {
       //I want to work with instance name and form there
    }
4

1 回答 1

1

最简单的方法是将 TextBox 实例附加到TagLinkLabel 控件的属性并在处理程序中访问它:

public static void startpage(Form form)
{
    try
    {
        var Tip = new Label() { Text = "Input instance name",
            Location = new Point(50, 50), AutoSize = true };

        var InstanceInput = new TextBox() { Text = "INSTANCENAME", 
            Location = new Point(100, 70), MaxLength = 1000, Width = 200,
        BorderStyle=BorderStyle.FixedSingle};

        var StartConnection = new LinkLabel() { Text = "Connect", 
            Location = new Point(50, 100), AutoSize = true, Tag = InstanceInput };

        StartConnection.Click += new EventHandler(nextpage);

        Helpers.AddControlsOnForm(form,
            new Control[] {Tip,StartConnection,InstanceInput });

    }
    catch(Exception ex) 
    { MessageBox.Show("Error occured. {0}",ex.Message.ToString()); }
}

public static void nextpage(Object sender, EventArgs e)
{
   var text = ((sender as LinkLabel).Tag as TextBox).Text;
}

在任何情况下,您要么必须将实例存储在某处(在本例中为 Tag 属性),要么搜索表单的 Controls 集合并找到所需的控件。

于 2013-04-28T12:20:03.283 回答