views:

257

answers:

4

I have Form1 that has a textbox and a button. When user clicks the button in Form1, Form2 opens up with a label control that carries the value of textbox in Form1.

What i did is set the textbox modifier of Form1 to Public, but when i call the textbox name of Form1 in Form2, i get an error that says "The name "txtbx1" doesn't exist in the current context". I wonder why since i already set the modifier of txtbx1 to Public.

Quick Note: i tried to instantiate Form1 in Form2 as:

Form1 f1 = new Form1();

and then call

f1.txtbx1.text

The odd thing is Form1 could not be instantiated (not highlighting occurs). On the other hand if i do Form2 f2 = new Form2(); Form2 gets highlighted!

This is how i show Form2 from Form1:

        SetSalary salForm = new SetSalary();
        salForm.ShowDialog();

Note that SetSalary represents Form2.

Any help will be appreciated.

A: 

To instantiate Form1 from Form2, class Form1 must be declared as public class Form1, or at least internal class Form1 if they are in the same assembly (project).

f1.txtbx1.text won't work because c# is case-sensitive and the property is called Text, not text.

Alternatively, you can declare a constructor with a parameter in Form2, so that you don't have to expose the TextBox member as public:

public class Form2 : Form
{
    public Form2(string text)
    {
        txtbx1.Text = text; //txtbx1 does not need to be public
    }
}

Then in Form1 you call var f2 = new Form2("label text goes here");

Jay
A: 

Expose a public property (or set of properties, if you have more than one value to pass in) on Form2 which will then fill the textbox. This hides the implementation detail of how it is displayed, if at all, and it also follows the standard used by built-in form classes. Example:

public class SetSalary {
    public SetSalary() { }
    public string SalaryText {
        get { return txtbox1.Text; }
        set { txtbox1.Text = value; }
    }
}

Then, when launching SetSalary, you do this:

SetSalary form = new SetSalary();
form.SalaryText = srcTextBox.Text;
form.ShowDialog();
siride
+1  A: 

make a constructor for form2 that accept string and in calling new form2 pass form1.frm1Textbox.text to contructor then set it to form2.frm2Textbox.text

Form2 form = new Form2(frm1Textbox.text);

in form2 constructor

public class Form2 : Form
{
    public Form2(string text)
    {
        frm2Textbox.Text = text; 
    }
}
Space Cracker
A: 

Good approach is to use Model-View-Presenter pattern. If you are a beginner (I think You are) then You should learn the basics by-the-book. This can help You minimize bugs and bad engineering, and will also maximize Your skill.

Turek