gujju_sale
gujju_sale

Reputation: 25

Unable to compare int? to null

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.

Upvotes: 0

Views: 126

Answers (3)

Voicu
Voicu

Reputation: 1

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

Upvotes: 0

keenthinker
keenthinker

Reputation: 7830

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.

Upvotes: 1

davmos
davmos

Reputation: 9577

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

int ipclass;
if (!int.TryParse(parts[0], out ipclass))
{
    //do nothing
}

Upvotes: 3

Related Questions