0

我们可以将数据列值分配给变量并以不同的方法使用该变量吗?我有以下代码

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

我可以这样做吗?或者有什么方法可以将数据 set.tables["ABC"].rows[0]["col name"] 值直接分配给 x

4

2 回答 2

0

如果您在方法之外创建变量,您将能够在类中的任何位置使用它。

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

如果您使用的是 Asp.net,请参阅有关在 Viewstate 中存储值的 user608576 答案。

于 2011-07-14T18:45:46.290 回答
0

由于您没有指定它是 Web 应用程序还是窗口应用程序,我将按以下方式回答 ASP.NET。

在这种情况下,页面会回发您的变量将丢失。因此,您可以保留值的唯一方法是将其添加到视图状态/会话/作为查询字符串传递到同一页面或将其置于某些隐藏控件中。

在 ASP.NET 中保存从一个页面加载到下一个页面的变量的最常用方法是将它们存储在作为隐藏输入的视图状态中。

您可以在 ViewState 中存储一个项目,例如:

ViewState[key] = value;

And retrieve it like:

value = ViewState[key]

或者

Session["username"] = username

And access it 

String Username = Session["username"];

如果它的 Window 应用程序可以有一个全局变量,它将在事件之间保留。

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

}

于 2011-07-14T18:44:25.193 回答