Insert null from TextBox to integer Field

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
 
G

Guest

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
}
 
A

avnrao

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.
 
K

Kevin Spencer

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.
 
P

Patrick Delifer

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
 
Joined
Oct 13, 2008
Messages
1
Reaction score
0
In WindowsForms I was able to do that this way:

txtNummer.DataBindings["Text"].NullValue = "";
 

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

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,540
Members
45,025
Latest member
KetoRushACVFitness

Latest Threads

Top