Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

How to change text in a textbox on another form in Visual C#?

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();


    }
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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 textbox (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();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...