How to create a global variable in C#? - c#

I need to use a global variable in my .net project. However, i cannot handle it between two methods..
my code:
string str;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
str = "i am a string";
showString();
}
}
void showString()
{
aspLabel.Text = str; //error
}
Question update:
I will not consider to use showString(str) because this variable is used many methods.. For example, I have a click event which need to use it.
protected void Btn_Click(object sender, EventArgs e)
{
exportToExcel(str);
}
Therefore, I need to create it in global!

The answer is don't do global variables (you also can't).
Closest to Global is having it in a class that is static and has a static member - but I really think it would be the wrong approach for most of the cases. Static classes/members usually make code more coupled and reduces testability so pick carefully when you decide to do so.
Do instead: (pass parameter)
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
string str = "i am a 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 am a string";
showString();
}
}
protected void Btn_Click(object sender, EventArgs e)
{
exportToExcel(str);
}
void showString()
{
aspLabel.Text = str;
}
}
Here you can change the str to be a property or a different access modifier as you wish, but this is the general idea.
If you have it as public instead of private you will be able to access it from different classes that hold an instance to this class. like this:
public class SomeClass
{
public string Str { get; private set; }
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Str = "i am a 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;
}
}

As has been said, don't do global variables. Instead pass a parameter into the method.
To make it slightly more obvious what is happening:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
string str = "i am a string";
showString(str);
}
}
void showString(string nowthis) // nowthis == str, value is copied in
{
aspLabel.Text = nowthis;
}

There's no notion of a global variable in C#.
You can have static members like this
public static class MyClassWithStatics
{
public static string MyString {get;set;}
}
Then, in another class, you can reference it:
public class MyOtherClass
{
public void MyMethod()
{
var str = MyClassWithStatics.MyString;
}
}

Related

How to Access variable from different method in C#?

How can I access variables on page_load and use it on ddlApp_SelectedIndexChanged method in c#?
thank you
private void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ddlRole.SelectedIndex = 0;
}
string ddl = ddlApp.Value.ToString();
string ddlRoleDs;
string ddlMenuDs;
string GvDs;
if (ddl == "ATTD")
{
ddlRoleDs = "ddlAttdDs";
ddlMenuDs = "ddlMenuAttdDs";
GvDs = "AttdMenuAssignmentDs";
}
else if (ddl == "TRVL")
{
ddlRoleDs = "ddlTrvldDs";
ddlMenuDs = "ddlMenuTrvlDs";
GvDs = "TrvlMenuAssignmentDs";
}
}
the variable: ddlRoleDs, GvDs and ddMenuDs
protected void ddlApp_SelectedIndexChanged(object sender, EventArgs e)
{
ddlRole.DataSourceID = ddlRoleDs;
MenuAssignmentGv.DataSourceID = GvDs;
ddlMenu.DataSourceID = ddlMenuDs;
}
You can use private global members in your class. This way they can only be accessed from within the class. The code below shows you exactly how to declare and use them
private string ddlRoleDs;
private string GvDs;
private string ddMenuDs;
private void Page_Load(object sender, EventArgs e)
{
// don't declare them here, but you can use them here
ddlRoleDs = "test value";
....
}
After the values were set in the Page_load method, they can be used in your other method
protected void ddlApp_SelectedIndexChanged(object sender, EventArgs e)
{
ddlRole.DataSourceID = ddlRoleDs;
MenuAssignmentGv.DataSourceID = GvDs;
ddlMenu.DataSourceID = ddlMenuDs;
}

alter ViewState of aspx.cs from simple cs

If you had to communicate a value between two classes in asp.net, an aspx.cs and a simple .cs class, and the value has to be present throughout the user's session, how would you do it?
the second class uses ViewState, I would like to alter the value of ViewState["VARIABLE1"] of class C2.aspx.cs from C1.cs, is that possible and how?
C1 doesn't have a C1.aspx (it's not a user control but a simple class. Thank you for the advice.
Here's the key:
the value has to be present throughout the user's session
Clearly, the main home for the variable should be in the session:
Session["VARIABLE1"]
However, I also see this:
I would like to alter the value of ViewState["VARIABLE1"] of class C2.aspx.cs from C1.cs
I suggest re-thinking C1.cs to use a more functional style. Design the classes there such that instead of something like this:
void C1Function()
{
if (Session["VARIABLE1"] == "value")
Session["VARIABLE1"] = somevalue;
}
///...
class C2
{
void Page_Load(object sender, EventArgs e)
{
C1TypeInstance.C1Function();
}
}
you instead end up with code more like this:
string C1Function(sting VARIABLE1)
{
if (VARIABLE1== "value")
return somevalue;
return VARIABLE1;
}
///...
class C2
{
void Page_Load(object sender, EventArgs e)
{
Session["VARIABLE1"] = C1TypeInstance.C1Function(Session["VARIABLE1"]);
}
}
or like this:
public class C1
{
private string variable1;
public C1(string VARIABLE1)
{
variable1 = VARIABLE1;
}
string C1Function()
{
if (variable1 == "value")
variable1 = somevalue;
return variable1
}
}
///...
class C2
{
void Page_Load(object sender, EventArgs e)
{
var C1TypeInstance = new C1(Session["VARIABLE1"]);
Session["VARIABLE1"] = C1TypeInstance.C1Function();
}
}
or like this:
static string C1Function(sting VARIABLE1)
{
if (VARIABLE1== "value")
return somevalue;
return VARIABLE1;
}
///...
class C2
{
void Page_Load(object sender, EventArgs e)
{
Session["VARIABLE1"] = C1Type.C1Function(Session["VARIABLE1"]);
}
}
And if all else fails, you can store an entire instance of your C1 type in the session, like this:
public class C1
{
public string VARIABLE1 {get; set;}
}
///...
class C2
{
void Page_Load(object sender, EventArgs e)
{
Session["VARIABLE1"] = Session["VARIABLE1"] ?? new C1();
((C1)Session["VARIABLE1"]).VARIABLE1 = "somevalue";
}
}

Make a local variable value global in c#

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.
}
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
}
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()
{
}
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";
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;
}
}
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)
{
}
}

Passing variable from one button click to another

This is a simple question but I can't seem to find an answer. I want to use the stored value from one button click to another within the same form. Any assistance would greatly be appreciated. I tried using an example from Calling code of Button from another one in C# but could not get it to work.
public struct xmlData
{
public string xmlAttribute;
}
private void Show_btn_Click(object sender, EventArgs e)
{
xmlData myXML = new xmlData();
//do something.....
myXML.xmlAttributes = "blah"
}
private void Submit_btn_Click(object sender, EventArgs e)
{
//I want to call myXML.xmlAttributes retrieving the stored value from Show_btn_Click
}
You should declare myXML variable at higher level of scope.
xmlData myXML = new xmlData();
public struct xmlData
{
public string xmlAttribute;
}
private void Show_btn_Click(object sender, EventArgs e)
{
//do something.....
myXML.xmlAttributes = "blah"
}
private void Submit_btn_Click(object sender, EventArgs e)
{
//I want to call myXML.xmlAttributes retrieving the stored value from Show_btn_Click
}
Instanciate the xmlData in the Constructor so you can access it overall in the class.
public class XYZ
{
xmlData myXML;
public XYZ()
{
myXML = new xmlData();
}
private void Show_btn_Click(object sender, EventArgs e)
{
//do something.....
myXML.xmlAttributes = "blah"
}
private void Submit_btn_Click(object sender, EventArgs e)
{
// Here you can work myXML.xmlAttributes
}
}

C#: String as parameter to event?

I have a GUI-thread for my form and another thread that computes things.
The form has a richtTextBox. I want the worker-thread to pass strings to the form, so that every string is displayed in the textbox.
Everytime a new string is generated in the worker thread I call an event, and this should now display the string.
But I don't know how to pass the string! This is what I tried so far:
///// Form1
private void btn_myClass_Click(object sender, EventArgs e)
{
myClass myObj = new myClass();
myObj.NewListEntry += myObj_NewListEntry;
Thread thrmyClass = new Thread(new ThreadStart(myObj.ThreadMethod));
thrmyClass.Start();
}
private void myObj_NewListEntry(Object objSender, EventArgs e)
{
this.BeginInvoke((MethodInvoker)delegate
{
// Here I want to add my string from the worker-thread to the textbox!
richTextBox1.Text += "TEXT"; // I want: richTextBox1.Text += myStringFromWorkerThread;
});
}
///// myClass (working thread...)
class myClass
{
public event EventHandler NewListEntry;
public void ThreadMethod()
{
DoSomething();
}
protected virtual void OnNewListEntry(EventArgs e)
{
EventHandler newListEntry = NewListEntry;
if (newListEntry != null)
{
newListEntry(this, e);
}
}
private void DoSomething()
{
///// Do some things and generate strings, such as "test"...
string test = "test";
// Here I want to pass the "test"-string! But how to do that??
OnNewListEntry(EventArgs.Empty); // I want: OnNewListEntry(test);
}
}
Like this
public class NewListEntryEventArgs : EventArgs
{
private readonly string test;
public NewListEntryEventArgs(string test)
{
this.test = test;
}
public string Test
{
get { return this.test; }
}
}
then you declare your class like this
class MyClass
{
public delegate void NewListEntryEventHandler(
object sender,
NewListEntryEventArgs args);
public event NewListEntryEventHandler NewListEntry;
protected virtual void OnNewListEntry(string test)
{
if (NewListEntry != null)
{
NewListEntry(this, new NewListEntryEventArgs(test));
}
}
}
and in the subscribing Form
private void btn_myClass_Click(object sender, EventArgs e)
{
MyClass myClass = new MyClass();
myClass.NewListEntry += NewListEntryEventHandler;
...
}
private void NewListEntryEventHandler(
object sender,
NewListEntryEventArgs e)
{
if (richTextBox1.InvokeRequired)
{
this.Invoke((MethodInvoker)delegate
{
this.NewListEntryEventHandler(sender, e);
});
return;
}
richTextBox1.Text += e.Test;
}
I've taken the liberty of making the NewListEntryEventArgs class immutable, since that makes sense. I've also partially corrected your naming conventions, simplified and corrected where expedient.
You need to create a new class by inheriting off EventArgs.
Create your own version of the EventArgs.
Do it like this:
public class MyEventArgs : EventArgs
{
public string MyEventString {get; set; }
public MyEventArgs(string myString)
{
this.MyEventString = myString;
}
}
Then in your code replace the EventArgs with MyEventArgs and create an MyEventArgs object with your string in it.
Then you can access it by using the MyEventArgs instance .MyEventString.
So you would do something like this:
///// myClass (working thread...)
class myClass
{
public event EventHandler NewListEntry;
public void ThreadMethod()
{
DoSomething();
}
protected virtual void OnNewListEntry(MyEventArgs e)
{
EventHandler newListEntry = NewListEntry;
if (newListEntry != null)
{
newListEntry(this, e);
}
}
private void DoSomething()
{
///// Do some things and generate strings, such as "test"...
string test = "test";
OnNewListEntry(new MyEventArgs(test));
}
}
And in your form:
private void myObj_NewListEntry(Object objSender, MyEventArgs e)
{
this.BeginInvoke((MethodInvoker)delegate
{
// Here I want to add my string from the worker-thread to the textbox!
richTextBox1.Text += e.MyEventString;
});
}
In general you need to inherit EventArgs and add a string property, and then make your event of type EventHandler<YourEventArgs>, but that is a classic case for the BackgroundWorker.
Sample here:
http://msdn.microsoft.com/en-us/library/cc221403(v=vs.95).aspx
and here:
C# backgroundWorker reports string?

Categories

Resources