【问题标题】:Placeholder losing data after postback回发后占位符丢失数据
【发布时间】:2018-06-08 03:48:22
【问题描述】:

我正在将数据库表中的 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++;
        }
}

【问题讨论】:

  • 能否显示您检索这些文本框的按钮单击事件?
  • @Win,btnsearch 是我创建文本框并将数据读入其中的地方
  • 动态添加的控件必须在下一个 page_load 期间再次添加。
  • 与这个问题无关,但请了解如何使用 CSS 为元素添加填充,而不是使用这样的不间断空格...您的代码的未来维护者将感谢您: )。

标签: c# asp.net


【解决方案1】:

这是在 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++;
    }
}

【讨论】:

  • 我收到此错误 { 或 ;预期的,我没有看到我缺少的东西。在本地机器上工作正常,但我在服务器上安装时出现错误
  • @Jane 它发生在哪几行? ControlCache 属性?
  • get => (List)(Session["cachedControlsForPageX"] = (Session["cachedControlsForPageX"] as List) ?? new List());
  • @Jane 我已经使用该属性的 C# 7 前兼容实现更新了答案。
  • 可以在每次按钮点击时停止添加文本框;因为还想根据从下拉列表中选择的数字创建文本框来填充文本框的数量。如果我选择2;然后 3 然后它被添加到五个文本框
猜你喜欢
  • 2016-01-07
  • 2014-09-22
  • 2010-10-24
  • 2011-11-19
  • 2016-09-24
  • 1970-01-01
  • 2019-04-05
  • 2013-10-02
  • 2016-08-19
相关资源
最近更新 更多