How to save null value into a Column in Database

Posted by Nkkppp under C# on 12/25/2012 | Points: 10 | Views : 1555 | Status : [Member] | Replies : 5
Hi,

In My database there are few columns as

Empid(Pk,int,not null)
Deptid (int, null),
DeptName(varchar(50),null),
Location(varchar(50),null)

From the front end..I am displaying a combobox where the Display member is DeptName and ValueMember is DeptID.Combobox intial value is --Select--

So when user doesn't select any item from the combobox I want to insert/update database columns with null value.

I tried to do it by converting the selectedvalue to int and when the user doesn't select an item.It throws an error as it is null.

So how to insert null.




Responses

Posted by: Nkkppp on: 12/25/2012 [Member] Starter | Points: 25

Up
0
Down
My problem is I am using a stored procedure for Inserting/Updating the table in Nlayer application.

objEmployeeDetailsMaster.DeptID = Convert.ToInt32(cmbDepartmenttype.SelectedValue.ToString());

As you can see when I am trying to get the selectedvalue it throws an error as I am not selecting an item. Can u please help me with this.

Nkkppp, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Guna27 on: 12/25/2012 [Member] Starter | Points: 25

Up
0
Down
Try this Code..


if(cmbDepartmenttype.SelectedIndex>0)
{
//Conversion
}
else
{
//Assign the value as null
}

Guna..............

Nkkppp, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Sinisreedhar on: 12/25/2012 [Member] Starter | Points: 25

Up
0
Down
if(cmbDepartmenttype.SelectedItem.Text == "-SELECT-")
{
// set your database value null here
}

Ready to accept challenges at any time.....

Nkkppp, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Sandeepmhatre on: 12/26/2012 [Member] Starter | Points: 25

Up
0
Down
other alternate method to achieve this :

set default value of Deptid is null
if user not select any item from drop down list then don't pass a deptId parameter to stored procedure / query
then it will automatically set null value.
for setting default value to the column refer this link

http://sandeepmhatre.blogspot.com/2012/12/sql-constraints.html


Sandeep M,
Software Developer
Follow me on :
http://sandeepmhatre.blogspot.in

Nkkppp, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Pavanandey on: 12/26/2012 [Member] Bronze | Points: 25

Up
0
Down
set default value of Deptid is null
insert into score values (1,null,1,1,1)

use the above statement



Thanks
Pavan Kumar
Mark Answer if this fits the need

Nkkppp, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response