Transfer numbers in textbox to labels in another form c# windows forms

ぃ、小莉子 提交于 2019-12-13 04:32:52

问题


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.


来源:https://stackoverflow.com/questions/17811112/transfer-numbers-in-textbox-to-labels-in-another-form-c-sharp-windows-forms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!