我在需要更新的Label控件中有Panel控件。Panel和Label控件是动态创建的。现在,我需要找到一种在Panel中获取1Panel值的方法。
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的值?
发布于 2012-01-30 15:32:06
像标签这样的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);我也会通过面板对well面板控件执行此操作:
FlowPanel.Controls.Add(newpanel);发布于 2012-01-30 15:22:27
如果动态创建控件,则应该在每次生成页面时都这样做。最好的地方是在PreInit事件中。然后,您可以拥有事件和状态,就像OnLoad事件中的正常控件一样。
https://stackoverflow.com/questions/9066118
复制相似问题