gpt4 book ai didi

c# - 变量恢复到初始值

转载 作者:行者123 更新时间:2023-11-30 15:00:03 25 4
gpt4 key购买 nike

下面我去掉了不相关的代码。我创建了一个名为 printString 的字段。 calculateButton_Click 方法执行大量操作,然后我想使用 response.write 将其发送到适合打印的页面。然而,printString 变量似乎并没有停止成为“DEFAULT”。当我单击 printButton_Click 时,DEFAULT 是我空白页上显示的所有内容。修剪代码如下:

    public partial class _Default : System.Web.UI.Page
{
private string _printString = "DEFAULT";

protected void Page_Load(object sender, EventArgs e)
{
Response.Buffer = true;
}

protected void calculateButton_Click(object sender, EventArgs e)
{
_printString = "";

_printString = "HARRY POTTER™: THE EXHIBITION Invoice<BR>Today's date: " + DateTime.Today.ToString("dd/MM/yyyy") + "<BR>Visit date: " +
dateSelectedString + "<BR><BR><BR>Adult tickets: " + numAdult + "<BR>Child tickets: " + numChild + "<BR>Family Passes: " + numFamily +
"<BR>Payment method: " + paymentType + "<BR>Total to pay: $" + totalPrice.ToString("0.00");

}

protected void printButton_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Write(_printString);
Response.Flush();
Response.End();
}
}

最佳答案

单击 printButton 时,它使用设置变量时的值 DEFAULT

private string _printString = "DEFAULT";

是你的问题。当变量被修改时,您需要维护 printString 的状态。简单地将 _printString 分配给另一个值并不能持久化更改。您可以编写一个函数,在单击 printButton 时将 _printString 分配给正确的值,使用 ViewStateSession或者直接在 printButton 点击函数中赋值 _printString 如下所示。

protected void printButton_Click(object sender, EventArgs e)
{
_printString = "Harry Potter";

Response.Clear();
Response.Write(_printString);
Response.Flush();
Response.End();
}

将导致 Harry Potter 被写入页面。

要使用Session:

protected void calculateButton_Click(object sender, EventArgs e)
{
_printString = "HARRY POTTER™: THE EXHIBITION Invoice<BR>Today's date: " + DateTime.Today.ToString("dd/MM/yyyy") + "<BR>Visit date: " +
dateSelectedString + "<BR><BR><BR>Adult tickets: " + numAdult + "<BR>Child tickets: " + numChild + "<BR>Family Passes: " + numFamily +
"<BR>Payment method: " + paymentType + "<BR>Total to pay: $" + totalPrice.ToString("0.00");

Session["PrintString"] = _printString;
}

protected void printButton_Click(object sender, EventArgs e)
{
_printString = (string)Session["PrintString"];

Response.Clear();
Response.Write(_printString);
Response.Flush();
Response.End();
}

View 状态:

ViewState["PrintString"] = "HarryPotter";

然后要检索您可以简单地执行的值:

 _printString = (string)ViewState["PrintString"];

http://msdn.microsoft.com/en-gb/library/ms972976.aspx

关于c# - 变量恢复到初始值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15878048/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com