If you try to use a parameterizes query like this:
SqlCommand comm = new SqlCommand(); comm.CommandText = "insert into Authors (firstname, surname) values (@firstname,@surname)" comm.Parameters.AddWithValue("firstname", firstName.Text); comm.Parameters.AddWithValue("surname", surName.Text);
and if the text fields for firstName or surName are left blank, maybeyou
willget
somequery
error.This is because the value of the text field is 'null' but to insert a null value in to a database, you have to use DBNull.Value.
The easiest way round this is to insert the simple code below:
foreach (SqlParameter Parameter in comm.Parameters)
{
if (Parameter.Value == null)
{
Parameter.Value = DBNull.Value;
}
}
This will convert the null values from the object layer to DBNull values that are acceptable to the database.
Please mark the replies as answers if they help or unmark if not.
Feedback to us
progammer
Member
14 Points
124 Posts
problem in save in fields allow null
May 05, 2012 04:29 AM|LINK
hi for all
I have problem with some controlls
I have some fields in database allow nulls
when i press on save button without fill the textboxes
which is join with the fields
the compiler give me an error when i fill them
the insert statement executes as well
any one can tell me how can i handle this problem
many thanks
kirupa.v
Contributor
2070 Points
531 Posts
Re: problem in save in fields allow null
May 05, 2012 05:12 AM|LINK
Hi,
For that particular field while inserting u can use
Isnull(txtbox,0)
I take the textbox Id as txtbox.
Try this..
mr.crazy
Member
34 Points
79 Posts
Re: problem in save in fields allow null
May 05, 2012 05:38 AM|LINK
if (!string.IsNullOrEmpty(textbox.Text)) { //assignment statement }Frank Jiang ...
All-Star
16006 Points
1728 Posts
Microsoft
Re: problem in save in fields allow null
May 08, 2012 07:35 AM|LINK
If you try to use a parameterizes query like this:
SqlCommand comm = new SqlCommand(); comm.CommandText = "insert into Authors (firstname, surname) values (@firstname,@surname)" comm.Parameters.AddWithValue("firstname", firstName.Text); comm.Parameters.AddWithValue("surname", surName.Text);
and if the text fields for firstName or surName are left blank, maybe you will get some query error.This is because the value of the text field is 'null' but to insert a null value in to a database, you have to use DBNull.Value.
The easiest way round this is to insert the simple code below:
foreach (SqlParameter Parameter in comm.Parameters) { if (Parameter.Value == null) { Parameter.Value = DBNull.Value; } }This will convert the null values from the object layer to DBNull values that are acceptable to the database.
Feedback to us
Develop and promote your apps in Windows Store