I have an application that contains a textbox wherein my database could only accept an int value, which is the contact number. The contact number field is only optional, so an empty field couldn't be accepted because it's still a character and not a number. How could I fix this? Need help.

Recommended Answers

All 8 Replies

int? contactNumber = null;
if (myTextBox.Text != String.Empty) {
    contactNumber = Int32.Parse(myTextBox.Text);
}

// contactNumber is now either null or contains the number or an Exception was thrown because Parse was unable to convert what was entered.

Can you insert 0 (zero) instead of nothing (in case if user does not insert a number)?
I was thinking of using this code then:

string strValue = textBox1.Text.Trim();
            int intValue = 0;
            if (strValue != String.Empty)
                intValue = Convert.ToInt32(strValue);
            else
                intValue = 0;

It's a contact number. 0 is not suitable, so an empty value is necessary. Do I need to set it null if there's no value inputted? What if I display the table at front end? Would the null field be present at display? It's kinda weird.

Yes, insert null. When inserting into dataBase do:
if parameter is null: DBNull.Value;

I have done this

if (provincecontact.Text != "")
        {
            cmd.Parameters.Add("@text", SqlDbType.BigInt).Value = provincecontact.Text;
        }
        else
        {
            cmd.Parameters.Add("@text", SqlDbType.BigInt).Value = DBNull.Value;
        }

Is this correct?

Recently I tried changing my deprecated parameters to paramater.AddWithValue. It doesn't throw an exception even the data passed was empty. It inserts a 0 instead of a null automatically into the database. What's the difference with addwithvalue with just add?

Nothing. Only code looks a bit different. That C# code has nothing to do with DataBase and their types and null or not null values.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.