【问题标题】:How to persist user control values?如何持久化用户控制值?
【发布时间】:2013-09-25 06:54:50
【问题描述】:

我想保留用户控制值

如果我再添加一行,则以前的控件值不存在

我浏览了一些网站,但我无法清楚地理解

代码:

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>

【问题讨论】:

    标签: c# asp.net user-controls viewstate


    【解决方案1】:

    必须在每次回发时添加动态控件,以便 ViewState 可以保持其值。更多详情,请阅读 ASP.NET 页面生命周期。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-16
      • 1970-01-01
      • 2012-02-10
      • 2019-07-31
      • 2016-06-24
      • 2012-05-17
      • 1970-01-01
      • 2014-07-06
      相关资源
      最近更新 更多