Home > Software design >  Function ping that change labels c#
Function ping that change labels c#

Time:10-21

Guys i have this function that check if there any switch offline, but i have 24 switchs at the company that i work, so i made a function to every Ip, if ping returns 'Success' the label color change to Green if not change to Red...

So I pass a param like ping1("123.45.67.899"); but I would like to pass the value of the label to change the color...

Anyone could help me ? currently I did 24 ping functions I changed the names of the labels which are from 25 to 49

        public void ping1(string ip)
        {
            Ping ping = new Ping();
            PingReply reply = ping.Send(ip, 100);

            if (reply.Status.ToString() == "Success")
            {

                label25.BackColor = Color.LightGreen;
            }
            else
            {
                label25.BackColor = Color.Red;
            }
        }

CodePudding user response:

I was wrong to declare label as string, label has to be Label

        public void ping0(string ip, Label lab)
        {
            Ping ping = new Ping();
            PingReply reply = ping.Send(ip, 100);

            if (reply.Status.ToString() == "Success")
            {

                lab.BackColor = Color.LightGreen;
            }
            else
            {
                lab.BackColor = Color.Red;
            }
        }
    ```

CodePudding user response:

If you are using a seperate class to call the original function posted in your question, it would not work since label25 is not initialized in that class. If you put the snippet of code in the same class where all your labels are initialized (aka the .cs file for the form with the labels), you could write it like this.

Earlier you said you had at least 40 labels, so doing it like this would be a lot easier instead of calling that method so many times.

        public static void ping3(string ip)
        {
            Ping ping = new Ping();
            PingReply reply = ping.Send(ip, 100);

            if (reply.Status.ToString() == "Success")
            {

                label25.BackColor = Color.LightGreen;
                label26.BackColor = Color.LightGreen;
                // all other labels, it goes on.
            }
            else
            {
                label25.BackColor = Color.Red;
                label26.BackColor = Color.Red;
                // all other labels, it goes on.
            }
        }

The other code you posted would also work, but this would seem to make the most sense in this context.

  • Related