Insert null from TextBox to integer Field

  • Thread starter Thread starter Fraggle
  • Start date Start date
F

Fraggle

I have an asp.net page, I have a text box where people can enter an
integer (age). I wish to store this in a SQLServer Database. If the
person enters no age then I would store a NULL.

However if the textbox is left blank, I get an error
"[InvalidCastException: Cast from string "" to type 'Integer' is not
valid.]"

How can I work around this, and get the null into the db?

Cheers

Fragg
 
You have to use Convert.DBNul

For example (using a stored procedure)

int intValueFromTextBox = Convert.ToInt32(txtTextBox.Text)
if(intValueFromTextBox ==null

cmdInsertRecord.SelectCommand.Parameters["@nAge"].Value = Convert.DBNull

els

cmdInsertRecord.SelectCommand.Parameters["@nAge"].Value = intValueFromTextBox
}
 
how are you accessing db? with stored procedures? when setting the parameter
value check if the text box value is "" and set the value to null.
Av.
 
If you're using a SQL Statment, you can simply omit the column from the
INSERT SQL statement.

--
HTH,
Kevin Spencer
..Net Developer
Microsoft MVP
Big things are made up
of lots of little things.
 
What DB are you using? if you're using SQL, What type did you give to your
Age Column (int, string, etc?)make sure it matches the cast type you are
getting back from the DB.
Go to the Age COlumn in you table and select Allow Nulls.

let me know

Patrick

avnrao said:
how are you accessing db? with stored procedures? when setting the parameter
value check if the text box value is "" and set the value to null.
Av.

Fraggle said:
I have an asp.net page, I have a text box where people can enter an
integer (age). I wish to store this in a SQLServer Database. If the
person enters no age then I would store a NULL.

However if the textbox is left blank, I get an error
"[InvalidCastException: Cast from string "" to type 'Integer' is not
valid.]"

How can I work around this, and get the null into the db?

Cheers

Fragg
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top