Make a local variable value global in c# - 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)
{
}
}

Related

Why my method "ReadPrice" can't access to the string "name" in the method "ReadName" [duplicate]

I'm new to C# and I really need to know how to call/use a string from another method.
For example:
public void button1_Click(object sender, EventArgs e)
{
string a = "help";
}
public void button2_Click(object sender, EventArgs e)
{
//this is where I need to call the string "a" value from button1_click
string b = "I need ";
string c = b + a;
}
In this example I need to call string "a" defined in function button1_Click() from function button2_Click()
Usually you'd pass it as an argument, like so:
void Method1()
{
var myString = "help";
Method2(myString);
}
void Method2(string aString)
{
var myString = "I need ";
var anotherString = myString + aString;
}
However, the methods in your example are event listeners. You generally don't call them directly. (I suppose you can, but I've never found an instance where one should.) So in this particular case it would be more prudent to store the value in a common location within the class for the two methods to use. Something like this:
string StringA { get; set; }
public void button1_Click(object sender, EventArgs e)
{
StringA = "help";
}
public void button2_Click(object sender, EventArgs e)
{
string b = "I need ";
string c = b + StringA;
}
Note, however, that this will behave very differently in ASP.NET. So if that's what you're using then you'll probably want to take it a step further. The reason it behaves differently is because the server-side is "stateless." So each button click coming from the client is going to result in an entirely new instance of the class. So having set that class-level member in the first button click event handler won't be reflected when using it in the second button click event handler.
In that case, you'll want to look into persisting state within a web application. Options include:
Page Values (hidden fields, for example)
Cookies
Session Variables
Application Variables
A Database
A Server-Side File
Some other means of persisting data on the server side, etc.
You need to declare string a in the scope of the class, not the method, at the moment it is a "local variable".
Example:
private string a = string.Empty;
public void button1_Click(object sender, EventArgs e)
{
a = "help";
}
public void button2_Click(object sender, EventArgs e)
{
//this is where I need to call the string "a" value from button1_click
string b = "I need";
string c = b + a;
}
You can now access the value of your "private field" a from anywhere inside your class which in your example will be a Form.
Agree with #Devid 's answer but I prefer to create a class of required entities and then use them in entire solution without passing variable as argument.
Classname.variableName;
for ex-
Class argumentData{
public static string firstArg= string.Empty;
public static string secArg= string.Empty;
}
Say I am assigning data in function
void assignData()
{
argumentData.firstArg="hey";
argumentData.secArg="hello";
}
if I want to use it in another method then
void showData()
{
Console.WriteLine("first argument"+argumentData.firstArg);
Console.WriteLine("sec argument"+ argumentData.secArg);
}
Hope this helps!
Refactor that into a method call (or property) so you can access the value of a elsewhere in your application:
public String GetStringAValue() {
return "help";
}
public void button1_Click(object sender, EventArgs e) {
string a = GetStringAValue();
}
public void button2_Click(object sender, EventArgs e) {
string a = GetStringAValue();
string b = "I need";
string c = b + a;
}
Also note that you could be using implicit type declarations. In effect, these are equivalent declarations:
string a = GetStringAValue();
var a = GetStringAValue();
class SomeClass
{
//Fields (Or Properties)
string a;
public void button1_Click(object sender, EventArgs e)
{
a = "help"; //Or however you assign it
}
public void button2_Click(object sender, EventArgs e)
{
string b = "I need";
string c = b + (a ?? String.Empty); //'a' should be null checked somehow.
}
}
make is a class level variable (global variable) or create a getter and setter for String a, to name a couple options.
You can't do that. string a is a local variable declaration. It's called "local" because it is only accessible "locally" to the block in which it occurs.
To make the variable visible to both methods, you can create a field in the class containing the methods. If the methods are in different classes, though, the solution gets more complicated.
You can't do this because those variables are in different scopes (think it as being hidden). The only way to achieve this is to move a in the main form class:
public partial class Form1 : Form
{
string a;
// etc ...
}
you can use session here
public void button1_Click(object sender, EventArgs e)
{
string a = "help";
Session["a"]=a;
}
public void button2_Click(object sender, EventArgs e)
{
string d=Session["a"].ToString();
string b = "I need ";
string c = b + d;
}
You could save the variable into a file, then access the file later, like this:
public void button1_Click(object sender, EventArgs e)
{
string a = "help";
File.WriteAllText(#"C:\myfolder\myfile.txt", a); //Change this to your real file location
}
public void button2_Click(object sender, EventArgs e)
{
string d = File.ReadAllText(#"C:\myfolder\myfile.txt");
//this is where I need to call the string "a" value from button1_click
string b = "I need";
string c = b + d; //Instead of a, put the variable name (d in this case)
}
If you do that, just make sure to put this in your code: using System.IO;

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";
}
}

How to create a global variable in 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;
}
}

parsing a variable from class to class

I would like to parse a variable example number from one class to another as show in the code below:
public class Gettemp // is the "public" will affect the passing of variable operation?
{
public void temp(string temp)
{
temp = "123"; // things that i wanted to pass from this class
}
}
public partial class Form1 : Form
{
private void STARTbtn_Click(object sender, EventArgs e)
{
MessageBox.Show() // i wan to show the variables here
}
}
What about making that method return the temp value :
public string temp()
{
string temp = "123";
return temp; // things that i wanted to pass from this class
}
}
private void STARTbtn_Click(object sender, EventArgs e)
{
Gettemp _GetTemp = new Gettemp();
string temp = _GetTemp.temp();
MessageBox.Show(temp);
}

Categories

Resources