簡體   English   中英

C#獲取動態創建的控件的值

[英]C# get value of dynamically created control

我在Panel控件中有“ Label控件,需要更新。 PanelLabel控件是動態創建的。 現在,我需要找到一種方法來獲取Panel中1 Label的值。

C#代碼

            // Create Panel
            Panel newpanel = new Panel();
            newpanel.Name = "panel_" + reader.GetValue(0);
            newpanel.Size = new Size(200, 200);
            newpanel.BorderStyle = BorderStyle.FixedSingle;
            newpanel.Parent = FlowPanel;

            // Create Label
            Label newipaddress = new Label();
            newipaddress.Name = "lbl_ip_add";
            newipaddress.Text = reader.GetValue(3).ToString();
            newipaddress.Location = new Point(55, 175);
            newipaddress.Parent = newpanel;

-------------

foreach (Panel p in FlowPanel.Controls)
{
    string ip = !!! GET IP FROM LABEL !!!
    Ping pingSender = new Ping();
    IPAddress pingIP = IPAddress.Parse(ip);
    PingReply pingReply = pingSender.Send(pingIP);

    lbl_ping_1.Text = string.Format("Ping: {0}", pingReply.RoundtripTime.ToString());
    if ((int)pingReply.RoundtripTime < 150)
    {
        lbl_ping_1.BackColor = Color.Green;
    }
    else if ((int)pingReply.RoundtripTime < 200)
    {
        lbl_ping_1.BackColor = Color.Orange;
    }
    else
    {
        lbl_ping_1.BackColor = Color.Red;
    }
}

字符串ip需要從Label獲取IP。 IP為字符串格式,如您所見,它將轉換為IP地址。

如何獲取動態創建的Label的值?

諸如標簽之類的GUI工具實際上不應該保存數據,而應該僅顯示數據。 因此,根據您的情況,最好將標簽信息保存在局部變量或字典中。

無論哪種情況,都可以在面板的控件集合中搜索標簽的名稱(控件鍵):

string ip;
if (p.Controls.ContainsKey("ipLabel")) {
  ip = p.Controls["ipLabel"].Text;
}

假設您在創建標簽時將其命名為“ ipLabel”:

Label ipLabel = new Label();
ipLabel.Name = "ipLabel";

更新:

您還需要使用Controls集合將Controls添加到容器中,而不是設置ControlsParent

例:

newpanel.Controls.Add(newipaddress);

我也將面板與flowpanel控件一起執行此操作:

FlowPanel.Controls.Add(newpanel);

如果動態創建控件,則應該在每一代頁面上都執行此操作。 最好的方法是在PreInit事件中。 然后,您可以像OnLoad事件中的普通控件一樣具有事件和狀態。

暫無
暫無

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

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