Reputation: 728
I have the following code.In this code i am able to get the string value like 1,2,3 etc through the use of eventHandling.How i get the value is not important for now.What i need now is to be able to access this string value outside the page_load event like in the function myfun()
as given below.How do i acheive that.
protected void Page_Load(object sender, EventArgs e)
{
hfm mymaster = (hfm)Page.Master;
lcont lc = mymaster.getlcont();
lc.myevent += delegate(string st)
{
//slbl.Text = st;
string str =st;
}
}
protectd void myfun()
{
//i want to access the string value "st" here.
}
Upvotes: 1
Views: 17399
Reputation: 11233
You can do it in two ways as i see:
1) Pass as param:
protected void Page_Load(object sender, EventArgs e)
{
hfm mymaster = (hfm)Page.Master;
lcont lc = mymaster.getlcont();
lc.myevent += delegate(string st)
{
//slbl.Text = st;
string str =st;
myfunc(str); // pass as param
}
}
protectd void myfun(string str) // see signature
{
//i want to access the string value "st" here.
}
2) Make a class variable:
string classvariable;
protected void Page_Load(object sender, EventArgs e)
{
hfm mymaster = (hfm)Page.Master;
lcont lc = mymaster.getlcont();
lc.myevent += delegate(string st)
{
//slbl.Text = st;
string str =st;
classvariable = str; // set it here
}
}
protectd void myfun()
{
//i want to access the string value "st" here. // get it here
}
Upvotes: 1
Reputation: 1326
A single change can make it possible. declare str as global variable
public class Form1
{
string str = "";//Globel declaration of variable
protected void Page_Load(object sender, EventArgs e)
{
}
}
Upvotes: 1
Reputation: 216
Place your global (or class?) variable before the Page_Load or right after the Class declaration.
public partial class Index : System.Web.UI.Page
{
private string str = "";
protected void Page_Load(object sender, EventArgs e)
{
hfm mymaster = (hfm)Page.Master;
lcont lc = mymaster.getlcont();
lc.myevent += delegate(string st)
{
//slbl.Text = st;
str =st;
}
}
protectd void myfun()
{
//i want to access the string value "st" here.
//value of st has been passed to str already in page_load.
string newString = str;
}
}
Upvotes: 1
Reputation: 3175
You can make it public:
public - the member can be reached from anywhere. This is the least restrictive visibility. Enums and interfaces are, by default, publicly visible
Example
<visibility> <data type> <name> = <value>;
or
public string name = "John Doe";
Upvotes: 1
Reputation: 3663
In my experience, you would simply declare the variable you want global outside of the scope of the functions.
IE: Whatever / wherever they are contained.
string st; // St is declared outside of their scopes
protected void Page_Load(object sender, EventArgs e)
{}
protectd void myfun()
{
}
Upvotes: 1