can we assign a data column value to a variable and use this variable in different method. i have the following code
button_click()
{
create and fill data set as data adapter.fill(data set,"ABC");
and then
int x= data set.tables["ABC"].rows[0]["col name"] ;
}
and i have another method button_click2()
{
int y = x;
}
can i do this? or is there any way i can assign the data set.tables["ABC"].rows[0]["col name"] value directly to x
As you have not specified is it Web application or window application I will answer it as below for ASP.NET.
In this case page will do post backs your variable will be lost. so only way you can preserve values is by adding it to viewstate/session/pass as querystring to same page or put it in some hidden control.
The most chosen method for preserving variables in ASP.NET from one page load to the next is to store them in viewstate which is a hidden input.
You would store an item in the ViewState like:
ViewState[key] = value;
And retrieve it like:
value = ViewState[key]
OR
Session["username"] = username
And access it
String Username = Session["username"];
If its Window application you can have a global variable which will be preserved between events.
Public class Test{
private int x= 0;//this is global here.
button_click()
{
create and fill data set as data adapter.fill(data set,"ABC");
and then
x= data set.tables["ABC"].rows[0]["col name"] ;
}
and i have another method button_click2()
{
int y = x;
}
}
If you create the variable out side the method you will be able to use it anywhere within the class.
public class Test
{
private int ColValue {get;set;} //This is a property
button_click()
{
ColValue = Convert.ToInt(dataset.tables["ABC"].rows[0]["col name"].ToString()) ;
}
button_click2()
{
int y = ColValue ;
}
}
Please see user608576 answer about storing values in Viewstate if you are using Asp.net.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.