【问题标题】:Background color not restored for dynamically generated controls (ASP.NET)未为动态生成的控件恢复背景颜色 (ASP.NET)
【发布时间】:2011-08-10 10:47:31
【问题描述】:

我正在 ASP.net 中动态生成<TABLE>。根据某些事件,我需要突出显示(通过背景颜色)有问题的特定单元格<TD>,并取消突出显示任何先前选择的单元格。

遗憾的是,在每个事件之后,之前选择的单元格仍然突出显示。我编写了一小段代码,用 2 个按钮模拟了两个事件的实例,从而重现了我的问题。

创建表 ...

    protected void Page_Init(object sender, EventArgs e)
    {
        Table tbl = new Table();
        this.Controls.Add(tbl);

        TableRow row = new TableRow();
        tbl.Controls.Add(row);

        TableCell cell1 = new TableCell();
        cell1.Style.Add("background-color", "green");
        cell1.ID = "cell1";
        cell1.Text = "CELL 1";

        TableCell cell2 = new TableCell();
        cell2.Style.Add("background-color", "green");
        cell2.ID = "cell2";
        cell2.Text = "CELL 2";

        row.Controls.Add(cell1);
        row.Controls.Add(cell2);
    }

我在此事件中突出显示第一个单元格

    protected void Button1_Click(object sender, EventArgs e)
    {
        TableCell ctr1 = (TableCell)this.FindControl("cell1");
        ctr1.Style.Add("background-color", "yellow");
    }

我在此事件中突出显示第二个单元格。第一个单元格不应再突出显示,因为我刚刚在回发时重新创建了此表!

    protected void Button2_Click(object sender, EventArgs e)
    {
        TableCell ctr2 = (TableCell)this.FindControl("cell2");
        ctr2.Style.Add("background-color", "yellow");
    }

任何帮助或指点将不胜感激!实现预期效果的替代方法也将受到欢迎!

【问题讨论】:

  • 在 button2.click 中,您要求找到“cell2”控件,在按钮 1 中是“cell1”控件。检查
  • @Eric,谢谢!显式设置颜色确实解决了这里的问题,但是如果我删除这个显式代码,之前的高亮仍然存在。
  • @Eric,我已经更新了代码。
  • 它当然会保留,它不会改变它的颜色,直到你命令它。
  • 哦,我现在看到了这个问题。提交后颜色还剩多少?那是因为缓存内存:)

标签: css asp.net html-table background-color dynamic-controls


【解决方案1】:

ViewState 又回来困扰我了!

创建动态控件时设置EnableViewState = false 解决了这些问题。

在这里,ASP.net 正在从 ViewState 恢复背景颜色,在大多数情况下,这是您希望动态生成的控件的行为!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 2011-07-02
    • 2014-04-29
    • 2010-09-14
    • 2015-10-28
    • 2017-12-10
    相关资源
    最近更新 更多