开发者

using isDBNULL to store null back in the database

开发者 https://www.devze.com 2023-01-09 08:49 出处:网络
I have many TextBOX in asp.net which accepts the value from user and stores it to SQL DB through SQL SERVER..

I have many TextBOX in asp.net which accepts the value from user and stores it to SQL DB through SQL SERVER.. When the user does not enter the value in the textbox, Which means i can allow the null for that filed in the table, But if its integer variable it stores 0, thats because

int HostelFees ;
HostelFees = TextBox1.Text;
//function called to store the hostel fee
insertFee(hostelFees);

in Database it stores 0, which i dont want but it to be null.. I went through many documentations and understood only slightly about ISDBNULL, But still am confused regarding while inserting how i will insert null. :( and i am not using any stored procedure's.. infact in the function insertFee(hostelFees) i just use command.ExecuteNonQuery to insert it

Please can anyone give me proper explation or link which i refer. Thank开发者_运维知识库 you,


You should consider using int?, which is a nullable version of int. In that case, you can use the HostelFees.HasValue check to see if a null is stored, and HostelFees.Value to use the integer part.

Please note that in your sample you are directly storing a string value into an integer variable. That won't work. What you want is to parse it first, then store null if it's not an integer. Something like this:

int? HostelFees = null;
int parsedValue;

if (int.TryParse(TextBox1.Text, out parsedValue)) {
    HostelFees = parsedValue;
}

//function called to store the hostel fee
insertFee(hostelFees);

And instead of assigning the integer value directly to the DbParameter, you can use the following construction:

parameter.Value = (HostelFees.HasValue ? HostelFees.Value : DbNull.Value);


your integer value should be nullable, just add ? after type declaration

int? HostelFees ;
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号