在两个表单

时间:2015-12-21 17:11:25

标签: c# forms winforms

我正在使用C#开发一个Windows窗体应用程序,我试图将一个字符串从一个窗体传递到另一个窗体。我的字符串似乎传递到第二种形式但是,当我尝试在第二种形式上将该字符串显示为标签时,它不显示字符串。但是,当我尝试在第二个表单上的消息框中显示它时,它会在消息框中显示传递的字符串。如何更改我的代码,以便我可以使用传递的字符串作为第二种形式的标签显示?

这是我的代码:

我的form1包含,

 private void Report_Bug_Click(object sender, EventArgs e)
    {
        ReportForm newForm = new ReportForm();
        string myString = "Hello World!";// string to be passed
        newForm.AuthUser = myString; //sending the string to the second form
        newForm.Show();
    }

我的form2(Reportform)包含,

public partial class ReportForm : Form
{
    public string AuthUser { get ; set; } //retrieving passed data

    public ReportForm()
    {
        InitializeComponent();
        populateListBox();
        userlabel.Text = AuthUser; //setting the label value to "Hello World!" - This doesn't work
    }

    private void Report_Submit(object sender, EventArgs e)
    {
        MessageBox.Show(AuthUser);// This displays a message box which says "Hello World!" so the string is passed
    }
}

如何更改我的代码,使其成为标签" userlabel"将显示我从第一个表单传递的字符串?

4 个答案:

答案 0 :(得分:3)

在设置AuthUser属性之前,在Form中设置标签文本。您可以让ReportForm构造函数接受该字符串。

public ReportForm(string labelText)
    {
        InitializeComponent();
        populateListBox();
        userlabel.Text = labelText;
    }

我假设你不再需要AuthUser了。

答案 1 :(得分:1)

^CI4行不应位于第二种格式的userlabel.Text = AuthUser;方法中。它是您的类的构造函数,在您将ReportForm()分配给myString之前执行它。最简单的方法是将newForm.AuthUser放在Form_Load()之类的事件处理程序中。您还可以更改构造函数以将该字符串作为参数接收,并将其显示在标签中。

答案 2 :(得分:1)

在Report_Bug_Click中设置AuthUser属性之前,执行ReportForm上的构造函数。您可以通过将字符串直接传递给重载的构造函数来解决此问题:

public ReportForm() {}

public ReportForm(string authUser)
{
    this.AuthUser = authUser
    InitializeComponent();
    populateListBox();
    userlabel.Text = this.AuthUser;
}

在Form1中,您在构造函数中传递字符串:

private void Report_Bug_Click(object sender, EventArgs e)
{
    ReportForm newForm = new ReportForm("Hello World!");
    newForm.Show();
}

答案 3 :(得分:1)

或者,使用Andy的建议,将字符串作为参数传递给构造函数:

    string myString = "Hello World!";// string to be passed
    ReportForm newForm = new ReportForm(myString);


public ReportForm(string text)
{
    InitializeComponent();
    populateListBox();
    userlabel.Text = text; 
}