Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
654 views
in Technique[技术] by (71.8m points)

c# - Passing values between two windows forms

The case is this, I have two different forms from the same solution/project. What I need to do is to extract the value of a label in Form A and load it into Form B. As much as possible, I am staying away from using this code since it will only conflict my whole program:

FormB myForm = new FromB(label.Text);
myForm.ShowDialog();

What I am trying right now is a class with a property of get and set for the value I wanted to pass. However, whenever I access the get method from FormB, it returns a blank value.

I hope somebody can help me with this. Any other ways to do this is extremely appreciated. :)

    public class Miscellaneous
    {
       string my_id;

       public void SetID(string id)
       {
           my_id = id;
       }

       public string GetID()
       {
           return my_id;
       }
     }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could do something like this:

Child form

public string YourText { get; set; }

public TestForm()
{
    InitializeComponent();
}

public void UpdateValues()
{
    someLabel.Text = YourText;
}

Initiate it

var child = new TestForm {YourText = someTextBox.Text};

child.UpdateValues();

child.ShowDialog();

With this approach you don't have to change the Constructor, you could also add another constructor.

The reason for them being empty is that the properties are set after the constructor, you could Also do someting like this to add a bit of logic to your getters and setters, However, I would consider not affecting UI on properties!

private string _yourText = string.Empty;
public string YourText
{
    get
    {
        return _yourText;
    }
    set 
    { 
        _yourText = value;
        UpdateValues(); 
    }
}

In this case, the UI will be updated automaticly when you set the property.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...