从动态创建的控件中检索值 asp .net 中的标签

本文关键字:asp net 标签 检索 动态 控件 创建 | 更新日期: 2023-09-27 18:37:18

>我在单击按钮时动态创建了标签控件:

protected void createDynamicLabels_Click(object sender, EventArgs e)
{
    int n = 5;
    for (int i = 0; i < n; i++)
    {
        Label MyLabel = new Label();
        MyLabel.ID = "lb" + i.ToString();
        MyLabel.Text = "Labell: " + i.ToString();
        MyLabel.Style["Clear"] = "Both";
        MyLabel.Style["Float"] = "Left";
        MyLabel.Style["margin-left"] = "100px";
        Panel1.Controls.Add(MyLabel);
    }
}

当我尝试读回另一个按钮时,我看到标签控件返回空

Label

str = (Label)Panel1.FindControl("lb" + i.ToString());

不知道这里出了什么问题

protected void bReadDynValue_Click(object sender, EventArgs e)
{
  int n = 5;
    for (int i = 0; i < n; i++)
    {
        Label str = (Label)Panel1.FindControl("lb" + i.ToString());
        lbGetText.Text = str.Text;
    }

}

从动态创建的控件中检索值 asp .net 中的标签

这是每次页面加载事件的问题。 ASP.net 每次单击任何按钮时触发页面加载事件。

假设在这个例子中..

protected void Page_Load(object sender, EventArgs e)
{
    if(!IsPostBack)
        createDynamicLabels();
}

private void createDynamicLabels()
    {
        int n = 5;
        for (int i = 0; i < n; i++)
        {
            Label MyLabel = new Label();
            MyLabel.ID = "lb" + i.ToString();
            MyLabel.Text = "Labell: " + i.ToString();
            MyLabel.Style["Clear"] = "Both";
            MyLabel.Style["Float"] = "Left";
            MyLabel.Style["margin-left"] = "100px";
            Panel1.Controls.Add(MyLabel);

        }
    }
protected void bReadDynValue_Click(object sender, EventArgs e)
{
    int n = 5;
    for (int i = 0; i < n; i++)
    {
        Label str = (Label)Panel1.FindControl("lb" + i.ToString());
        lbGetText.Text = str.Text;
    }

}

当按钮触发器页面没有任何标签时,因为它是在运行时制作的。 并且页面找不到特定标签。 如果您尝试上述代码,它会正常运行。

 protected void Page_Load(object sender, EventArgs e)
{
        createDynamicLabels();
}

private void createDynamicLabels()
    {
        int n = 5;
        for (int i = 0; i < n; i++)
        {
            Label MyLabel = new Label();
            MyLabel.ID = "lb" + i.ToString();
            MyLabel.Text = "Labell: " + i.ToString();
            MyLabel.Style["Clear"] = "Both";
            MyLabel.Style["Float"] = "Left";
            MyLabel.Style["margin-left"] = "100px";
            Panel1.Controls.Add(MyLabel);

        }
    }
protected void bReadDynValue_Click(object sender, EventArgs e)
{
    int n = 5;
    for (int i = 0; i < n; i++)
    {
        Label str = (Label)Panel1.FindControl("lb" + i.ToString());
        lbGetText.Text = str.Text;
    }

}

在此示例中,代码每次都查找标签,因为每次都可以为此页面制作标签。

动态创建的标签仅在下一次回发发生之前存在。单击另一个按钮检索其值时,将发生回发,值变为 null。

为了在回发后保存标签状态,您必须使用一些隐藏字段。

如果 labes 的文本/值没有改变,则在每次回发时生成它们就足够了(正如 mck 已经提到的)。如果需要检索在客户端所做的更改,则应在 OnInit 事件而不是 PageLoad 中创建控件,并使用输入/文本框而不是标签。

另一种选择(我推荐)是使用 asp:Repeater 来生成标签。