简体   繁体   中英

How can I change the label text in form "a" when a button is pressed in form "b" .net C#

I was wondering if someone could help?

The goal of DataEntryForm is to return a string to form1.

  1. The DataEntryForm is created and opened when btnOpen is pressed which is located on form1.
  2. The value in the text box in DataEntryForm should be returned to form1 when btnOK is pressed.

I've tried using event handlers so far but not had any luck. Any suggestions?

数据输入表单

表格一

My favorite way to do this is to encapsulate the logic in a static method of the form. Static methods have access to the form's private members so you don't have to worry about exposing anything in public properties.

class DataEntryForm : Form
{
    /* The rest of your class goes here */

    public static string Execute()
    {
        using (var form = new DataEntryForm())
        {
            var result = form.ShowDialog();
            return (result == DialogResult.OK) ? form.MyTextBox.Text : null;
        }
    }
}

Then in form1, all you have to do is this:

var enteredText = DataEntryForm.Execute();

Add a public property InputValue to the DataEntryForm. When user clicks the button on the form assign the property and close the DataEntryForm:

this.InputValue = textbox.Text;

Opening and reading the value:

DataEntryForm formDE = new DataEntryForm();
formDE.ShowDialog();

if (formDE.DialogResult == DialogResult.OK)
{
   // ok result
   string value = formDE.InputValue
   formDE.Dispose();
}
else
{
   //cancel
   formDE.Dispose();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM