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

后端 未结 7 1978
抹茶落季
抹茶落季 2020-12-02 01:30

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 d

相关标签:
7条回答
  • 2020-12-02 01:57

    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();
    }
    
    0 讨论(0)
提交回复
热议问题