簡體   English   中英

c# asp.net 用於將 int 值附加到標簽 id

[英]c# asp.net for append int value to the label id

我有以下帶有 ID 的標簽:

<asp:Label ID="FromName0" runat="server"  Visible="true"></asp:Label>
<asp:Label ID="FromName1" runat="server"  Visible="true"></asp:Label>
<asp:Label ID="FromName2" runat="server"  Visible="true"></asp:Label>
<asp:Label ID="FromName3" runat="server"  Visible="true"></asp:Label>
<asp:Label ID="FromName4" runat="server"  Visible="true"></asp:Label>

我想使用 for 循環將值分配給標簽 ID。 我在 c# 中使用以下標簽:

for (int i = 0; i < count; i++)
{
var label = this.Controls.Find("FromName " + i, true) as Label;
label.Text = Session["DeliverAddress" + i].ToString();
}

但是“查找”顯示如下錯誤:System.Web.UI.ControlCollections 沒有“查找”的定義。 但我已經添加了'System.Web.UI' dll 文件。 誰能幫我?

我正在使用 dotnet 框架 4.0。

提前致謝。

你可以這樣做

  public  Control[] FlattenHierachy(Control root)
    {
        List<Control> list = new List<Control>();
        list.Add(root);
        if (root.HasControls())
        {
            foreach (Control control in root.Controls)
            {
                list.AddRange(FlattenHierachy(control));
            }
        }
        return list.ToArray();
    }

protected void Page_Load(object sender, EventArgs e)
    {
        Control[] allControls = FlattenHierachy(Page);
        foreach (Control control in allControls)
        {
            Label lbl = control as Label;
            if (lbl != null && lbl.ID == "FromName0")
            {
                lbl.ID = "myid";//Do your like stuff
            }
        }
    }

只需使用: 這里關於 FindControl 的 MSDN 文章

    //
    // Summary:
    //     Searches the page naming container for a server control with the specified identifier.
    //
    // Parameters:
    //   id:
    //     The identifier for the control to be found.
    //
    // Returns:
    //     The specified control, or null if the specified control does not exist.
    public override Control FindControl(string id);

您的代碼應該如下所示。 就像建議檢查控件是否為 null會話變量是否為 null 一樣,這可能會給您一個異常。

for (int i = 0; i < count; i++)
{
    var label = FindControl("FromName " + i) as Label;

    if(label == null || Session["DeliverAddress" + i] == null)
       continue;

    label.Text = Session["DeliverAddress" + i].ToString();

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM