Why program freezes when I add instance of Form in user control in C#? -
i new c# , using windows forms. have form1
button (button_save) , textbox
. , have user control1 1 button (button1
).
what trying in program is: when click on button1
, text appear in textbox
(in form1
), enter new text , click save, button1
text change accordingly.
i explain when freeze happens:
there 2 parts:
first part: when created instance of user control1 in form1
participated in usercontrol1event
, run program works fine , button1
text appears in textbox
when click on it. second part when create instance of form1
in user control1 , participated in form1event , run program program freezes long time gives error pointing @ form1
instance in user control1 (as shown in screen shot).
anyone knows why happening ? doing wrong?
form1:
public partial class form1 : form { public event eventhandler form1event; usercontrol1 uc1 = new usercontrol1(); public form1() { initializecomponent(); controls.add(uc1); uc1.visible = true; uc1.usercontrol1event += new eventhandler(handleuc1); } string return_textbox_txt; public string textbox_txt { { return return_textbox_txt; } } public void handleuc1(object sender, eventargs e) ////////////handle uc1 event { textbox1.text = uc1.buttontext; } private void button_save__click(object sender, eventargs e)//change button text { return_textbox_txt = textbox1.text; form1event(this, e); } }
user control1:
public partial class usercontrol1 : usercontrol { string btntxt; form1 frm1 = new form1(); public event eventhandler usercontrol1event; public string buttontext { { return btntxt; } } private void usercontrol1_load(object sender, eventargs e) { frm1.form1event += new eventhandler(handleform1event); } public void handleform1event(object sender, eventargs e) { button1.text = frm1.textbox_txt; } private void button1_click(object sender, eventargs e) { btntxt = button1.text; usercontrol1event(this, e); } }
it's expected behavior because of creating new form1
instance , on object constructing creates new usercontrol1
instance creates new form1
instance , on.
if need have owner of usercontrol1
inside instance can pass usercontrol1
constructor:
public partial class form1 : form { ... usercontrol1 uc1; public form1() { initializecomponent(); // creates new control , pass owner via constructor parameter uc1 = new usercontrol1(this); controls.add(uc1); uc1.visible = true; uc1.usercontrol1event += new eventhandler(handleuc1); } ... } public partial class usercontrol1 : usercontrol { form1 frm1; public usercontrol1(form1 owner) { // save user control owner passed constructor parameter local variable frm1 = owner; } ... }
Comments
Post a Comment