asp.net - How to create a global variable in C#? -
i need use global variable in .net project. however, cannot handle between 2 methods..
my code:
string str; protected void page_load(object sender, eventargs e) { if (!page.ispostback) { str = "i string"; showstring(); } } void showstring() { asplabel.text = str; //error }
question update:
i not consider use showstring(str)
because variable used many methods.. example, have click event need use it.
protected void btn_click(object sender, eventargs e) { exporttoexcel(str); }
therefore, need create in global!
the answer don't global variables (you can't).
closest global
having in class static
, has static
member - think wrong approach of cases. static
classes/members make code more coupled , reduces testability pick when decide so.
do instead: (pass parameter)
protected void page_load(object sender, eventargs e) { if (!page.ispostback) { string str = "i string"; showstring(str); } } void showstring(string str) { asplabel.text = str; }
or:
public class someclass { private string str; protected void page_load(object sender, eventargs e) { if (!page.ispostback) { str = "i string"; showstring(); } } protected void btn_click(object sender, eventargs e) { exporttoexcel(str); } void showstring() { asplabel.text = str; } }
here can change str
property or different access modifier wish, general idea.
if have public instead of private able access different classes hold instance class. this:
public class someclass { public string str { get; private set; } protected void page_load(object sender, eventargs e) { if (!page.ispostback) { str = "i string"; showstring(); } } protected void btn_click(object sender, eventargs e) { exporttoexcel(str); } void showstring() { asplabel.text = str; } } public class someotherclass { public someotherclass() { someclass someclass = new someclass(); var otherstr = someclass.str; } }
Comments
Post a Comment