Home > Enterprise >  How to more efficiently set properties of multiple Form Controls
How to more efficiently set properties of multiple Form Controls

Time:07-02

My problem is that I have multiple Forms Controls that I need to make visible/invisible/change text, based on the output of my code.

Obviously this is very easy to achieve but the code is ridiculously long due to how I've set it up.

I have 3 image boxes containing a red, green and orange 'light'.

When the ping action is started (button click or a timer) all the controls need to be set like so:

// ping 1
redLight1.Visible = true;
greenLight1.Visible = false;
orangeLight1.Visible = false;
status_Lbl1.Text = "Initiated...";

I need to do this 9 times, and the code looks a bit meh to me having this repeated this many times.

I have a ping object that sends a ping every second for x amount of time. If all of the pings are sent and received successfully then an imagebox containing a green circle becomes visible greenLight1.Visible = true, while all others are set redLight1.Visible = false, orangeLight1.Visible = false, etc.

I have 9 of these sets of 'traffic lights', with a different IP being pinged and a different outcome for each.

I feel there must be a way to iteratively change the values of each of these boxes using the fact they all follow the same naming convention with just a different number on the end corresponding to the ping object they represent.

Here's a more visual idea of what I want to achieve.

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  
            }
        }
    }
}

Here's the method that creates/uses the ping objects just in case that is necessary

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());
    }
}

CodePudding user response:

You can use Controls.Find() and "search by name" with the recurse option:

Control ctl = this.Controls.Find("greenLight"   counter, true).FirstOrDefault() as Control;
if (ctl != null) {
    ctl.Visible = false;
}
  • Related