在c#中将动态字符串从一个表单传递到另一个表单

时间:2013-11-22 07:07:37

标签: c# winforms backgroundworker

我有两种表单Form1Form2

在Form1中我有一个backgroundWorker

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        backgroundWorker1.RunWorkerAsync();
        Form2 frm2 = new Form2();
        frm2.Show();
    }

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        int k = 0;bool b=true;
        while (b==true)
        {
            Thread.Sleep(100);
            k++;
            backgroundWorker1.ReportProgress(0, "data");
            if (k >= 100)
                b = false;
        }
    }

    private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        string str = "";
        str+=e.UserState.ToString();
        label1.Text += str;
    }
}

Form2我有一个标签label2

如何动态在表单2的label2上的form1中显示label1的相同内容。

请帮助举例。

1 个答案:

答案 0 :(得分:0)

更新Action上的label时,您可以拨打Form1

public Action<string> UpdateFormAction {get; set;}   

private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    string str = "";
    str+=e.UserState.ToString();
    label1.Text += str;
    UpdateForm2(label1.Text);
}

private void UpdateForm2(string text)
{
   Action<string> handler = UpdateFormAction;
   if (handler != null)
       handler(text);
}

然后,根据您实例化表单的位置,您可以连接Action