占位符在回发后丢失数据

时间:2018-06-07 16:38:29

标签: c# asp.net

我正在将数据库表中的ID号列表读入占位符文本框但是;如果我按下按钮,则删除数据。

 protected void btnSearch_Click(object sender, EventArgs e)
    {

     while (myReader.Read())
        {


            TextBox txt = new TextBox();
            txt.Text = (string)myReader["idNumber"];
            txt.ID = "txt" + i;
            txt.ReadOnly = true;
            ContentPlaceHolder1.Controls.Add(txt);
            ContentPlaceHolder1.Controls.Add(new LiteralControl("     "));

            i++;
        }
}

1 个答案:

答案 0 :(得分:0)

在Web表单中使用动态添加的控件时,这是一个常见问题(特别是如果您来自winforms背景)。 ASP.NET Web窗体中的页面是无状态的,并在每个回发时重建。因此,如果在服务器事件期间向页面添加控件,则还必须在后续页面加载时将其添加到页面中(如果要显示)。您可以使用类似于以下内容的方式完成此任务:

protected List<Control> ControlCache
{
    get => (List<Control>)(Session["cachedControlsForPageX"] = (Session["cachedControlsForPageX"] as List<Control>) ?? new List<Control>());
    set => Session["cachedControlsForPageX"] = value;
}

/* If you can't use C# 7's expression bodied property accessors, here's the equivalent in blocks:
protected List<Control> ControlCache
{
    get { return (List<Control>)(Session["cachedControlsForPageX"] = (Session["cachedControlsForPageX"] as List<Control>) ?? new List<Control>()); }
    set { Session["cachedControlsForPageX"] = value; }
}
*/

protected void Page_Load(object sender, EventArgs e)
{
    if (Page.IsPostBack)
    {
        foreach (var control in ControlCache)
        {
            ContentPlaceHolder1.Controls.Add(control);
            ContentPlaceHolder1.Controls.Add(new LiteralControl("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"));
        }
    }
    else
        ControlCache = null;
}


protected void btnSearch_Click(object sender, EventArgs e)
{
    while (myReader.Read())
    {
        TextBox txt = new TextBox();
        txt.Text = (string)myReader["idNumber"];
        txt.ID = "txt" + i;
        txt.ReadOnly = true;
        ContentPlaceHolder1.Controls.Add(txt);
        ContentPlaceHolder1.Controls.Add(new LiteralControl("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"));
        ControlCache.Add(txt);
        i++;
    }
}