Click here to Skip to main content
16,021,172 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i have a form in which there are some fields name,last name,birthday etc.some fields are optional i-e last name,birthday etc.i want to store null value in database if user don't fill these optional fields.how can i do this?in c# windows app
Posted

Just use a parameterised query (as you should with all user input to prevent SQL Injection problems) and pass DBNull.Value:
C#
using (SqlCommand cmd = new SqlCommand("INSERT INTO MyTable (MyColumn) VALUES (@VAL)", con))
    {
    object val = tbUserInput.Text;
    if (string.IsNullOrWhiteSpace(tbUserInput.Text)) val = DBNull.Value;
    cmd.Parameters.AddWithValue("@VAL", val);
    ...
    }
 
Share this answer
 
v2
Comments
Nainaaa 15-Sep-14 14:12pm    
this is for the string.i want for the int type textboxes and combo boxes.
OriginalGriff 15-Sep-14 14:30pm    
It's
an
example
...


I'm not about to provide you with an example that covers every control and database type combination on the planet, now am I?
Do as OriginalGriff has said, but one more thing. Do not forget to allow the Null values in the column which setting the Database table schema. So that if you're passing a Null value, it might/should not raise an error saying, it was expecting a value not a null.

By default non-primary, non-identity etc columns allow the null value and primary identity and key columsn don't allow null. They always require some value to work on.

So, when you're using the above code, you must allow null to be added in the column.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900