一个很基础的问题,但是很奇怪!大家来帮忙看看!!

gbl777 2003-04-04 02:45:44
我建立一个简单的asp.net项目(myTest)
在页面index.aspx中加入一个label,两个button.
定义了一个静态变量currentRow,主要来跟踪currentRow的变化!
我同时打开两个页面,分别进行操作!
假设在页面一里,当前值是3,页面二里当前值是1,我在页面二里点击了一下"下一条"
按钮,结果就变成了4,两个页面会相互影响,请问这是为什么?

以下是源程序:
namespace myTest
{
/// <summary>
/// WebForm1 的摘要说明。
/// </summary>
public class WebForm1 : System.Web.UI.Page
{
protected System.Web.UI.WebControls.Button buttonNext;
protected System.Web.UI.WebControls.Button buttonPreview;
protected System.Web.UI.WebControls.Label labelLocation;

protected static int currentRow;

private void Page_Load(object sender, System.EventArgs e)
{
// 在此处放置用户代码以初始化页面
if(!this.IsPostBack )
{
currentRow=-1;
DisplayLocation();
}
}
#region Web Form Designer generated code

//显示当前位置
protected void DisplayLocation()
{
string i = Convert.ToString (currentRow+1);
labelLocation.Text = "当前位置:"+i+"/10";
}

//显示上一条
private void buttonPreview_Click(object sender, System.EventArgs e)
{
if(currentRow>0)
{
currentRow--;
}

DisplayLocation();


}

//显示下一条
private void buttonNext_Click(object sender, System.EventArgs e)
{
if(currentRow<9)
{
currentRow++;
}

DisplayLocation();


}
}
}


...全文
15 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
Knight94 2003-04-04
  • 打赏
  • 举报
回复
如果你的currentRow是全局的,那么注意各个对象对它操作;
如果只是对象属性的话,但要为了给人提供访问的方法,那不妨这样:
private int currentRow;
public int getCurrentRow()
{
return currentRow;
}
public void setCurrentRow(int nCurrentRow)
{
currentRow=nCurrentRow;
}
gbl777 2003-04-04
  • 打赏
  • 举报
回复
但是在一个页面内我需要把currentRow设置成静态变量!

那该怎么班?
Knight94 2003-04-04
  • 打赏
  • 举报
回复
你用static定义的变量对于一个应用程序域中是全局的,所以当页面一改为3时,页面二虽然显示为1,但currentRow的值已经为3了,因此出现你所说的现象。
Knight94 2003-04-04
  • 打赏
  • 举报
回复
你用的是static的缘故,改成
protected int currentRow;就行了

110,500

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧