开发者

Writing to a textbox on a separate form (C#)

Suppose I have two forms: Form1 and Form2. Form2 has a text control开发者_运维技巧 named text1

In VB6 I could write to Form 2's textbox

control from Form1 by using: Form2.Text1.text = "Some text here"

How can I make this work in C#? I have tried everything!

What I have tried:

Form2 Frm2 = new Form2();
Frm2.show();
Frm2.Activate(); // Trying everything to make sure it sees the form (it does).

Frm2.Text1 (Doesn't find the control)...

ANSWER:

I ended up making a public routine in Form2, and then just calling this routine from form1. In this public routine of Form2 I would then call the textbox!


I believe all form elements are private by default. So you're going to have to switch their definition to public (in your .designer.cs) or make a public getter and setter for each textbox you want to access.


You need to keep a reference to the second form in the first form.

// form1 code 
// variables
Form2 myForm2;
// Form1_Loaded event handler
myForm2 = new Form2();
myForm2.Show();
// place where you want to change text on form2 from within form1
myForm2.Text1.Text = "Some text here";


You have to have a reference to the instance of Form2 in order to write to it. Pass the reference to the instance of Form2 to Form1 and then manipulate it like you are expecting. You can pass this instance in via the constructor or you can pass it in later. You can also store the instance reference in a central location. Just be sure that you don't create a new instance of Form2 when you try to access the instance. For example, if you put the following code in your form:

Form2 myInstance = new Form2();

then you will be creating a new instance of Form2, which probably isn't what you want.


My goal was add text to a Text Box on another form. I had Form1 and Form2. Form2 has a text box control named Text1. In order to make this work, I created a Sub Routine:

public Void WriteToText(string sData)
{
// Here is where I wrote to my textbox
Text1.text = sData;
}

Form 1 code:

Form2 Frm2 = new Form2();
Frm2.WriteToText("My Data");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜