2013-09-25 70 views
0

我要保持用戶的控制值如何保持用戶控制值?

如果我增加一個行之前的控制值是不存在

我通過一些網站走了,但我不能清楚地瞭解

代碼:

protected void Page_Load(object sender, EventArgs e) 
    {  
     if (!IsPostBack) 
     { 
      ViewState["ControlCount"] = ViewState["ControlCount"] == null ? 2 : ViewState["ControlCount"]; 
     } 
    } 

    public int controlCount 
    { 
     get 
     { 
      int val = 0; 
      try 
      { 
       val = (int)ViewState["ControlCount"]; 
      } 
      catch (Exception e) 
      { 
       // handle exception, if required. 
      } 
      return val; 
     } 
     set { ViewState["ControlCount"] = value; } 
    } 

在這裏,我添加的用戶控件

protected void addnewtext_Click(object sender, EventArgs e) 
    { 
     int i = controlCount++; 

     for (int j = 0; j <= i; j++) 
     { 
      AddVisaControl ac = (AddVisaControl)Page.LoadControl("AddVisaControl.ascx"); 
      Label lb = new Label(); 
      string z = Convert.ToString(j + 1); 
      lb.Text = "Visa " + z; 
      rpt1.Controls.Add(lb); 
      lb.Attributes.Add("class", "style8"); 
      rpt1.Controls.Add(ac); 
      rpt1.Controls.Add(new LiteralControl("<BR>"))  
     } 
    } 

AddVisaUserControl.ascx

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="AddVisaControl.ascx.cs" EnableViewState="false" Inherits="Pyramid.AddVisaControl" %> 
<div id="divreg" runat="server"> 
<table id="tbl" runat="server"> 
    <tr> 
    <td> 
     <asp:Label ID="lbl2" runat="server"></asp:Label> 
    </td> 
</tr> 
<tr> 
<td> Visa Number:</td> 
<td><asp:TextBox ID="txtUser" Width="160px" runat="server"/></td> 
<td> Country Name:</td> 
<td><asp:DropDownList ID="dropCountry" Width="165px" runat="server"></asp:DropDownList></td> 
</tr> 
<tr> 
<td> Type of Visa:</td> 
<td><asp:DropDownList ID="dropVisa" Width="165px" runat="server"></asp:DropDownList></td> 
<td> Type of Entry:</td> 
<td><asp:DropDownList ID="dropEntry" Width="165px" runat="server"></asp:DropDownList></td> 
</tr> 
<tr> 
<td> Expiry Date</td> 
<td> 

</td> 
</tr> 
</table> 
</div> 

回答

0

動態控制必須在每個回發被添加,使得視圖狀態可以保持其值。有關更多詳細信息,請閱讀ASP.NET頁面生命週期。