将数据传输到处理程序

时间:2013-04-28 11:37:47

标签: c# .net winforms

我有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
    }

1 个答案:

答案 0 :(得分:1)

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

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属性)或搜索表单的控件集合并找到所需的控件。