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
Joey Calisay - 16 Sep 2004 15:48 GMT
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();
}
> Hello,
>
[quoted text clipped - 41 lines]
> Thanks in advance!
> Tinus
Tinus - 16 Sep 2004 17:05 GMT
Thanks. But I get the following error when compiling:
Cannot implicitly convert type 'System.Windows.Forms.Control' to
'myTestApp.UserControl1'
??
Tinus
> It's because you're manipulating different instances of UserControl1.
> First instance : one added to panel
[quoted text clipped - 56 lines]
> > Thanks in advance!
> > Tinus
Joey Callisay - 17 Sep 2004 10:59 GMT
my mistake it should have been this one:
Button2_ClickEvent(..)
{
UserControl1 uc = Form1.Panel1.Controls[0] as UserControl1;
uc.UpdateTextBox();
}
> Thanks. But I get the following error when compiling:
> Cannot implicitly convert type 'System.Windows.Forms.Control' to
[quoted text clipped - 68 lines]
> > > Thanks in advance!
> > > Tinus