Dan Cook
Dan Cook

Reputation: 11

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?

DataEntryForm

form1

Upvotes: 0

Views: 102

Answers (2)

John Wu
John Wu

Reputation: 52280

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();

Upvotes: 1

mjefim
mjefim

Reputation: 44

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:

using (var formDE = new DataEntryForm()) 
{ 
    if (formDE.ShowDialog() == DialogResult.OK) 
    { 
        // access the returned value
        string value = formDE.InputValue
    } 
},

Upvotes: 1

Related Questions