我的问题是,我有多个表单控件,我需要使可见/不可见/改变文本,基于我的代码输出。
显然这很容易实现,但由于我的设置方式,代码长得离谱。
我有3个图像框,包含红色,绿色和橙色的"光"。
ping操作开始时所有控件(按钮单击或一个计时器)需要设置一样:
// ping 1
redLight1.Visible = true;
greenLight1.Visible = false;
orangeLight1.Visible = false;
status_Lbl1.Text = "Initiated...";
我需要这样做9次,代码看起来有点无聊,因为这个重复了很多次。
我有一个ping对象,它在x时间内每秒发送一个ping。如果所有ping都成功发送和接收,则包含绿色圆圈的图像盒变为可见greenLight1.Visible = true
,而所有其他图像盒则设置为redLight1.Visible = false
,orangeLight1.Visible = false
等。
我有9组这样的"交通灯",有不同的IP被ping,每个都有不同的结果。
我觉得一定有一种方法可以迭代地改变这些盒子的值,因为它们都遵循相同的命名约定,只是在它们所代表的ping对象的末尾对应不同的数字。
这是我想要实现的一个更直观的想法。
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
// int counter = 0
if (e.Cancelled == true)
{
status_Lbl1.Text = "Cancelled";
}
else if (e.Error != null)
{
status_Lbl1.Text = "Error: " + e.Error.Message;
}
else
{
foreach (Ping pingObj in pings)
{
if (pingObj.SuccessfulPings == 0)
{
Debug.WriteLine("Ping Object: " + pingObj.Fqdn + " failed to successfully ping");
// greenLight[i].Visible = false;
// orangeLight[i].Visible = false;
// redLight[i].Visible = true;
// counter++
}
else if (pingObj.FailedPings != 0)
{
Debug.WriteLine("Ping Object: " + pingObj.Fqdn + " failed to successfully ping: " + pingObj.FailedPings + " times.");
// greenLight[i].Visible = false;
// orangeLight[i].Visible = true;
// redLight[i].Visible = false;
// counter++
}
else
{
Debug.WriteLine("Ping Object: " + pingObj.Fqdn + " succesfully pinged: " + pingObj.SuccessfulPings + " times.");
// greenLight[i].Visible = false;
// orangeLight[i].Visible = false;
// redLight[i].Visible = false;
// counter++
}
}
}
}
下面是创建/使用ping对象的方法,以防必要
private async void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
try
{
// Create background worker
BackgroundWorker worker = (BackgroundWorker)sender;
// Write to log file
await file.WriteAsync("Starting job...n");
await file.WriteAsync("Requested amount of pings: " + count + "n");
// Create date object for logs
DateTime localDate = DateTime.Now;
for (int i = 0; i < count; i++)
{
// Create ping objects
System.Net.NetworkInformation.Ping pinger = new System.Net.NetworkInformation.Ping();
PingReply pingReply;
try
{
foreach (Ping pingObj in pings)
{
try
{
pingReply = pinger.Send(pingObj.IpAddress);
// Write log file
await file.WriteLineAsync(localDate.TimeOfDay + " | Friendly Name " + pingObj.FriendlyName + " | Ping: " + pingReply.Address + " | Status " + pingReply.Status + " | Time: " + pingReply.RoundtripTime);
if (pingReply.Status.ToString().Contains("Success"))
{
pingObj.SuccessfulPings += 1;
}
else // Unsuccessful ping has been sent
{
pingObj.FailedPings += 1;
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.ToString());
}
}
wait(1000);
}
catch (Exception b)
{
Debug.WriteLine(b.ToString());
}
}
}
catch (Exception a)
{
Debug.WriteLine(a.ToString());
}
}
您可以使用Controls.Find()
和"按名称搜索";recurse
选项:
Control ctl = this.Controls.Find("greenLight" + counter, true).FirstOrDefault() as Control;
if (ctl != null) {
ctl.Visible = false;
}