如何获取表单中的标签以显示属性的值

时间:2018-11-11 17:38:12

标签: c#

在C#Windows窗体中,我有2个窗体。我想在表单上的标签中显示字符串的集合。调试时,我在数组中显示了2个元素,但它们没有显示在传递给我的标签中。当我将鼠标悬停在toString上时,数据已经存在,但是如何将其传递给发件人,以便其显示在我在表单上的标签控件中?

Details of what I am trying to pass

在下面的数据代码段中,数据位于toString中,但是如何从那里到sender.ToString?

   public AccountReport_cs(Func<string> toString)
    {
        this.toString = toString;


    }

    private void AccountReport_cs_Load(object sender, EventArgs e)
    {

        label1.Text = sender.ToString();
    }

这是另一段将打开要在其中显示信息的form2的代码。

        private void reportButton2_Start(object sender, EventArgs e)
    {
        AccountReport_cs accountReport = new AccountReport_cs(allTransactions.ToString);
        accountReport.ShowDialog();
    }

这是最后一段代码,它将显示数据如何到达EndOfMonth。

    public class Transaction
{
    public string EndOfMonth { get; set; }
}

        public override List<Transaction> closeMonth()
        {
            var transactions = new List<Transaction>();
            var endString = new Transaction();

                endString.EndOfMonth = reportString;
            transactions.Add(endString);

            return transactions;
        }

1 个答案:

答案 0 :(得分:2)

如果需要在表单之间发送信息,最好的办法是在目标表单中创建一个属性,并在显示表单之前分配要发送的值;因此,您无需更改表单的默认构造函数。

// Destiny form
public partial class FormDestiny : Form {
    // Property for receive data from other forms, you decide the datatype
    public string ExternalData { get; set; }

    public FormDestiny() {
        InitializeComponent();
        // Set external data after InitializeComponent()
        this.MyLabel.Text = ExternalData;
    }
}

// Source form. Here, prepare all data to send to destiny form
public partial class FormSource : Form {
    public FormSource() {
        InitializeComponent();
    }

    private void SenderButton_Click(object sender, EventArgs e) {
        // Instance of destiny form
        FormDestiny destinyForm = new FormDestiny();
        destinyForm.ExternalData = PrepareExternalData("someValueIfNeeded");
        destinyForm.ShowDialog();
    }

    // Your business logic here
    private string PrepareExternalData(string myparameters) {
        string result = "";
        // Some beautiful and complex code...
        return result;
    }
}