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";
}
}
Related
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;
}
}
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);
}
I want to make an object that stores a reference to another object. I have a code like this:
public partial class Form1 : Form
{
int test = 1;
store st;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
st = new store(test);
}
private void button1_Click(object sender, EventArgs e)
{
test = 7;
}
private void button2_Click(object sender, EventArgs e)
{
label1.Text = Convert.ToString((int)st.o);
}
}
public class store
{
public object o;
public store(object obj)
{
o = obj;
}
}
If I click button2 - I can see "1" in my label. But if I click button2 and then button1 - I still see "1". How should I alter my code so I'll see "7" in that case?
When you create the store object you're evaluating the value of the test variable, and storing that value rather than the test variable. If you want to have a way of evaluating the variable to its value later, you can use a lambda to close over the variable, since closures in C# close over variables, not values.
public partial class Form1 : Form
{
int test = 1;
Store<string> store;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
store = new Store<string>(() => test.ToString());
}
private void button1_Click(object sender, EventArgs e)
{
test = 7;
}
private void button2_Click(object sender, EventArgs e)
{
label1.Text = store.GetValue();
}
}
public class Store<T>
{
private Func<T> function;
public Store(Func<T> function)
{
this.function = function;
}
public T GetValue()
{
return function();
}
}
Note that I made a few changes to the names of items to be in line with standard C# conventions, rather than having Store expose the generator function's field publicly, I provide a function that lets you get the value, and I've also made it generic, rather than using object, as this both avoids boxing, and prevents the need to cast the object returned from the store.
With minimal changes, here you go.
Properties and constructor of Form1:
public Form1()
{
st = new store(test);
}
private int testPrivate { get; set; }
public int test
{
get { return testPrivate; }
set
{
testPrivate = value;
st.o = value;
}
}
public store st { get; set; }
The store class:
public class store
{
public object o { get; set; }
public store(object obj)
{
o = obj;
}
}
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)
{
}
}
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
}
}