0

Look at this code which I surrounded by textchanged event of a text box:

        string testString = comboIPAddress.Text;
        string[] parts = testString.Split('.');
        int? ipclass = int.Parse(parts[0]);
        if (ipclass == null)
        {
            //do nothing
        }

        if (ipclass >= 1 && ipclass <= 126)
        {
            comboSubnet.Text = "255.0.0.0";
        }
        if (ipclass >= 192 && ipclass <= 223)
        {
            comboSubnet.Text = "255.255.255.0";
        }
        if (ipclass >= 128 && ipclass <= 191)
        {
            comboSubnet.Text = "255.255.0.0";
        }
        else
        {
            comboSubnet.Text = "";
        }

While executing the exe if I delete everything from IPAddress combo box, it is giving error(Input string was not in a correct format.). I don't know the other way to compare an int to null. Please help.

gujju_sale
  • 25
  • 1
  • 4

3 Answers3

3

Use non-nullable int and check if parsable with int.TryParse()...

int ipclass;
if (!int.TryParse(parts[0], out ipclass))
{
    //do nothing
}
davmos
  • 9,324
  • 4
  • 40
  • 43
1

Have you considered using a MaskedTextBox for the IP? You can then parse the input easily using the System.Net.IPAddress Parse method as shown in this SO answer.

Community
  • 1
  • 1
keenthinker
  • 7,645
  • 2
  • 35
  • 45
0

You should test if(!string.IsNullOrEmpty(testString)) before trying to split it, followed by int.TryParse

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Voicu
  • 1