Updating textbox from class that did not create the textbox?

Updating textbox from class that did not create the textbox?

Post by Tinu » Fri, 17 Sep 2004 20:52:01


Hello,

The following problem is driving me nuts :-(
Hopefully someone here can help me solving it...

I have created a form called Form1 (Form1.cs) and added a panel called
Panel1 on it. I also added two buttons called Button1 and Button2.

I added a UserControl to the project called UserControl1 (UserControl1.cs).
In this UserControl1 I created a panel with a textbox called TextBox1 with
default text "Hello world".

Button1 click event adds the UserControl1 to Panel1 (which belongs to
Form1):
UserControl1 uc = new UserControl1();
Panel1.Controls.Add(uc);

So far so good. After I clicked Button1 I see a form with a textbox "Hello
world" and two buttons.

Button2 click event calls a function in UserControl1 that changes the text
in TextBox1 to "Hello Universe". E.g.
public void UpdateTextBox()
{
TextBox1.Text = "Hello Universe";
}

So, in Form1 I have the following code for Button2 click event:
Button2_ClickEvent(..)
{
UserControl1 uc = new UserControl1();
uc.UpdateTextBox();
}

Now, when I press Button2 nothing happens! Why is this? When I change
UpdateTextBox() to only contain a MessageBox.Show(TextBox1.Text); I get a
MessageBox that is empty when I press Button2!? However I can see that
TextBox1 contains "Hello World" on Form1.

Can some tell me why the text in TextBox1 is not changed to "Hello
Universe"? And give me an example on how one should do this. I'm not a
professional coder....

Thanks in advance!
Tinus
 
 
 

Updating textbox from class that did not create the textbox?

Post by Joey Calis » Fri, 17 Sep 2004 23:48:54

It's because you're manipulating different instances of UserControl1.
First instance : one added to panel
Second instance : instantiated and (implicitly private) accessible only at
the Button2_ClickEvent method

You should revise your Button2_ClickEvent method to get the instance of
usercontrol from the panel of the form like

Button2_ClickEvent(..)
{
UserControl1 uc = Form1.Panel1.Controls[0];
uc.UpdateTextBox();
}




(UserControl1.cs).

 
 
 

Updating textbox from class that did not create the textbox?

Post by Tinu » Sat, 18 Sep 2004 01:05:29

Thanks. But I get the following error when compiling:
Cannot implicitly convert type 'System.Windows.Forms.Control' to
'myTestApp.UserControl1'

??

Tinus

"Joey Calisay" < XXXX@XXXXX.COM > schrieb im Newsbeitrag



with
"Hello
text
a
 
 
 

Updating textbox from class that did not create the textbox?

Post by Joey Calli » Sat, 18 Sep 2004 18:59:22

y mistake it should have been this one:

Button2_ClickEvent(..)
{
UserControl1 uc = Form1.Panel1.Controls[0] as UserControl1;
uc.UpdateTextBox();
}

"Tinus" < XXXX@XXXXX.COM > wrote in message
news:%23h7Z$ XXXX@XXXXX.COM ...
at
get