Featured post
c# - Multiple .cs files and access to Form -
i'm trying write first program in c# without use of tutorial. ensure adopt start coding practices, want create each class in different .cs file. however, i'm running troubles when trying access elements of program in such .cs file.
for example, have form1.cs label , start button. when clicking on start button, text should appear in label. so:
in form1.cs have:
namespace testprogram { public partial class form1 : form { public form1() { initializecomponent(); } private void startbutton_click(object sender, eventargs e) { writetolabel message = new writetolabel(); message.welcomemessage(); } } }
and in separate writetolabel.cs file:
namespace testprogram { public class writetolabel { public void welcomemessage() { form1 myform = new form1(); //myform.. --> myform doesn't have 'outputlabel'? outputlabel.text = "welcome!"; // returns error: 'the name outputlabel not exits in current context'. } } }
'outputlabel' (name) i've given label, , in accordance name in form1.designer.cs. both files using same components such 'using system';.
however, writetolabel.cs file can't seem access form holds program. did manage succeed create different .cs files in console application, added confusion. so, have 2 questions:
first, how can access form separate class (i.e. not partial class) in separate file? second, way it, or inefficient create multiple instances of different classes?
any thoughts or ideas highly welcome,
regards,
the designer automatically creates controls private fields, because of writetolabel class can't access it. need change that. start change class that:
namespace testprogram { public class writetolabel { form1 form; public writetolabel(form1 form) { this.form = form; } public void welcomemessage() { //form1 myform = new form1(); //myform.. --> myform doesn't have 'outputlabel'? form.outputlabel.text = "welcome!"; } } }
- Get link
- X
- Other Apps
Comments
Post a Comment