Transfer numbers in textbox to labels in another f

2019-09-06 14:20发布

问题:

How do you guys actually transfer a numeric value in textbox in Form 2 (which is double) to a label in another form(Form 1) in the correct way and this is what I've done:

//Form 2
private void btnok_Click(object sender, EventArgs e)
    {
        double exchange;
        exchange = Double.Parse(txtcurrent.Text);
        this.ownerForm.PassValue(txtcurrent.Text);
        this.Close();
    }
//Form 1
public void PassValue(string strValue)
    {
        lblexchange.Text = strValue;
    }
private void update_Click(object sender, EventArgs e)
    {
        if (fromcountry.Text == tocountry.Text)
        {
            MessageBox.Show(" Please Choose Two Different Currencies ", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }
        else
        {
            btnconvert.Enabled = true;
            Exchange_Rate frm = new Exchange_Rate();
            frm.Show();

        }

I got NullReferenceException was unhandled in the end. I don't know how to code it further. I need help

回答1:

You have to pass your Form1 reference to Show method. And then use `thi

btnconvert.Enabled = true;
Exchange_Rate frm = new Exchange_Rate();
frm.Show(this);

and then:

private void btnok_Click(object sender, EventArgs e)
{
    double exchange;
    exchange = Double.Parse(txtcurrent.Text);

    var frm = (Form1)this.Owner;
    frm.PassValue(txtcurrent.Text);

    this.Close();
}


回答2:

Please, do step as follows: (1) For that first open design file of form2 where label placed and change their declaration to public from private.

Than from form1, call directly to form2.label --> 

    form2.lblexchange.text = "PASS VALUE"

In this case, need to open form2 without creating object of form2.

If you want to create object of form2 for open form than at that time do code as below:



        Form2 obj = new Form2();
        obj.lblexchange.text = "PASS VALUE";
        obj.show();

Enter code here:

(2) method to solve using module. (VB project)
This method is very simple to use. Below:
--> Create module file enter code here.
--> Declare public variable (var1) in module file.
--> Set public variable (var1) from form1.
--> Form2_load event - set label (lblexchange) to var1.

I think above code will help you.