views:

567

answers:

3

In Visual C# when I click a button, I want to load another form. But before that form loads, I want to fill the textboxes with some text. I tried to put some commands to do this before showing the form, but I get an error saying the textbox is inaccessible due to its protection level.

How can I set the textbox in a form before I show it?

 private void button2_Click(object sender, EventArgs e)
    {

        fixgame changeCards = new fixgame();
        changeCards.p1c1val.text = "3";
        changeCards.Show();


    }
+3  A: 

When you create the new form in the button click event handler, you instantiate a new form object and then call its show method.

Once you have the form object you can also call any other methods or properties that are present on that class, including a property that sets the value of the textbox.

So, the code below adds a property to the Form2 class that sets your testbox (where textbox1 is the name of your textbox). I prefer this method method over making the TextBox itself visible by modifying its access modifier because it gives you better encapsulation, ensuring you have control over how the textbox is used.

    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

        public string TextBoxValue
        {
            get { return textBox1.Text;} 
            set { textBox1.Text = value;}
        }                       
    }

And in the button click event of the first form you can just have code like:

private void button1_Click(object sender, EventArgs e)
{
    Form2 form2 = new Form2();
    form2.TextBoxValue = "SomeValue";
    form2.Show();
}
David Hall
+1 even though its possible to change the modifiers on the textbox to public, its a better design to set the text using a property so that the OOP principles of information hiding is not broken. (in this case, hiding the textbox control from being modified outside the object).
Andrew Keith
A: 

You can set "Modifiers" property of TextBox control to "Public"

Laserson
A: 

In the designer code-behind file simply change the declaration of the text box from the default:

private System.Windows.Forms.TextBox textBox1;

to:

protected System.Windows.Forms.TextBox textBox1;

The protected keyword is a member access modifier. A protected member is accessible from within the class in which it is declared, and from within any class derived from the class that declared this member (for more info, see this link).

pFrenchie