在按钮上存储文本框中的字符串单击可在页面重新加载时使用该变量



如何在buttonclick上存储文本框输入,以便页面重载可以使用这些值来重新创建其某些内容?我尝试过使用viewState,但在使用断点时,它总是在page_load上显示null。

点击按钮:

protected void LoadLifeLineBtn_Click(object sender, EventArgs e)
{
    ViewState["lifelineID"] = Convert.ToInt32(TextBox1.Text);
    ViewState["phaseid"] = Convert.ToInt32(TextBox2.Text);
    this.Page_Load();
}

这是我的页面_加载

int lifelineid;
int phaseid;
protected void Page_Load(object sender, EventArgs e)
{
    hideAndShow();
    if (!IsPostBack)
    {
        lifelineid = 22222;
        phaseid = 1;
        FillFaseTable(PhaseMainTable, phaseid, lifelineid);
        PhasePanel.CssClass = "panel col-lg-2 col-md-2 col-xs-2 Phase1BackgroundColor";
    }
    else if (IsPostBack)
    {
        if (ViewState["lifelineid"] != null) 
        {
            lifelineid = (int)ViewState["lifelineid"];
        }
        if (ViewState["phaseid"] != null) 
        {
            phaseid = (int)ViewState["phaseid"];
        }
        FillFaseTable(PhaseMainTable, phaseid, lifelineid);
        PhasePanel.CssClass = "panel col-lg-2 col-md-2 col-xs-2 Phase1BackgroundColor";
    }
}

假设您的按钮已连接到此事件

<asp:Button ID="LoadLifeLineBtn" runat="server" OnClick="LoadLifeLineBtn_Click"></asp:Button>

您应该能够稍微改变一下这一点,以使代码流更加流畅。

protected void LoadLifeLineBtn_Click(object sender, EventArgs e)
{
    hideAndShow();
    int lifelineID = Convert.ToInt32(TextBox1.Text);
    int phaseid = Convert.ToInt32(TextBox2.Text);
    FillFaseTable(PhaseMainTable, phaseid, lifelineid);
    PhasePanel.CssClass = "panel col-lg-2 col-md-2 col-xs-2 Phase1BackgroundColor";
}

现在重新组织Page_Load事件以处理页面最初加载的时间

protected void Page_Load(object sender, EventArgs e)
{
    hideAndShow();
    if (!IsPostBack)
    {
        lifelineid = 22222;
        phaseid = 1;
        FillFaseTable(PhaseMainTable, phaseid, lifelineid);
        PhasePanel.CssClass = "panel col-lg-2 col-md-2 col-xs-2 Phase1BackgroundColor";
    }
}

原因是当LoadLifeLineBtn_Click触发时,您可以执行此时所需的操作,而不直接调用Page_Load事件。

我添加了第二个答案,以帮助解释单击LoadLifeLineBtn按钮时代码中发生的一些情况。

当您单击LoadLifeLineBtn时,它将触发LoadLifeLineBtn_Click事件,该事件将创建PostBack,并且输入到TextBox1TextBox2中的值将已经是ViewState的一部分。

在您的代码中,您可以将其更改为此,并且它应该按照您的意愿继续运行,而无需手动设置ViewState

protected void Page_Load(object sender, EventArgs e)
{
    int lifelineid;
    int phaseid;
    hideAndShow();
    if (!IsPostBack)
    {
        lifelineid = 22222;
        phaseid = 1;
    }
    else
    {
        lifelineID = Convert.ToInt32(TextBox1.Text);
        phaseid = Convert.ToInt32(TextBox2.Text);
    }
    FillFaseTable(PhaseMainTable, phaseid, lifelineid);
    PhasePanel.CssClass = "panel col-lg-2 col-md-2 col-xs-2 Phase1BackgroundColor";
}

最新更新