2016-04-14 16 views
1

如何在buttonclick上存儲文本框輸入,以便頁面重新加載可以使用這些值重新創建它的某些內容? 我已經嘗試使用viewState,但它總是隻在page_load上使用斷點時表示null。將文本框中的字符串存儲在buttonclick上以便在頁面重新加載時使用該變量

按鈕點擊:

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

而且我的繼承人的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"; 
    } 
} 
+0

以前有this.Page_load(null,null),因爲它需要一些東西。 我在LoadLifeLineBtn中使用this.Page_load的原因是因爲我需要爲viewstate設置值,但是比page_load已經完成了它的運行(因爲它在buttonclick之前完成) – svennand

+1

重構'else if(IsPostBack )'阻塞到一個方法中,然後調用該方法而不是調用'this.Page_Load()'。其實你只需要最後兩行。 – mshsayem

+0

是的!工作!謝謝 :) – svennand

回答

0

假設你的按鈕連接到這個事件

<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事件直。

0

我添加了第二個答案,以幫助解釋點擊LoadLifeLineBtn按鈕時代碼中發生的一些事情。

當您單擊LoadLifeLineBtn,它觸發了LoadLifeLineBtn_Click事件,這將創建一個回傳和值進入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"; 
} 
相關問題