Link to home
Start Free TrialLog in
Avatar of shpresa
shpresaFlag for United States of America

asked on

how to save a text field as null if missed

Hello Experts

I have a text field that can accept a range values from 0 - 10
If the question is missed it is stored a 0 value in the database, and I want know if I have a missed question or a zero value.

How can I save that field to be 'null' if missed.

This is how I have it currently.


            cmd.Parameters.Add(new SqlParameter("@Times", txtTimes.Text.Trim()));

on save click button.
Avatar of kaufmed
kaufmed
Flag of United States of America image

How about:

string s = txtTimes.Text.Trim();
object o = (s == "0" ? s : DBNull.Value);

cmd.Parameters.Add(new SqlParameter("@Times", o));

Open in new window

Sorry, flip-flop the operands in line 2:

object o = (s == "0" ? DBNull.Value, s);

Open in new window

Here is a good example of how to do it:

create procedure poc_name
@Questionnaire varchar(50)=NULL
,@OfficeSpace varchar(50)=NULL
,@PartnerID varchar(50)=NULL
AS
BEGIN
       
        SET NOCOUNT ON;
        Update tPartners
Set  
Questionnaire = @Questionnaire,
OfficeSpace = @OfficeSpace
where PartnerID = @PartnerID
END
Now that is a SQL Server script; you can do the same thing in C# though by passing NULL in your insert or update statements too.  Let me know if you want to see examples.
Too slow. ;)
First off make sure the field is 'nullable'.

Here is how you save it as null if it is blank.

string prmTimes = !string.IsNullOrEmpty(txtTimes.Text.Trim()) ? txtTimes.Text.Trim() : null;
cmd.Parameters.Add(new SqlParameter("@Times", prmTimes));

lol, I guess I was too slow too.
ASKER CERTIFIED SOLUTION
Avatar of kaufmed
kaufmed
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of shpresa

ASKER

Thanks..DBnull.value worked.