C#获取动态创建的控件的值

时间:2012-01-30 15:15:29

标签: c# winforms dynamic

我在Label控件中有Panel个控件需要更新。 PanelLabel控件是动态创建的。现在,我需要找到一种方法,以便在Label中获得1 Panel的值。

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

的值

2 个答案:

答案 0 :(得分:6)

像标签之类的GUI工具实际上不应该保持数据,它应该显示数据。因此,在您的情况下,将标签信息保存在局部变量或字典中会更好。

在任何一种情况下,您都可以在面板的控件集中搜索标签的名称(控制键):

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

这假定您在创建标签时将其命名为“ipLabel”:

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

<强>更新

您还需要使用Controls集合将控件添加到容器中,而不是设置控件的Parent

示例:

newpanel.Controls.Add(newipaddress);

我也可以使用面板进行流动面板控制:

FlowPanel.Controls.Add(newpanel);

答案 1 :(得分:0)

如果您动态创建控件,则应在每个页面生成时执行此操作。最好的地方是PreInit活动。然后,您可以像OnLoad事件中的普通控件一样拥有事件和状态。