1

I have a table that has a few columns that sometimes will have a null value. How can I check if a value is null, and if so set the value to an empty string or something that I can use later?

private DateTime dtDate_Ordered;
private DateTime dtDate_Required;
private DateTime dtDate_Received;

var stringSql = "select * from po where po_num=" + stringPO_NUM;

var Class_Connection = new SQL_Connection();

Class_Connection.cnn.Close();
Class_Connection.cnn.Open();

try
{
    var cmd = new SqlCommand(stringSql, Class_Connection.cnn);
    SqlDataReader sdr = cmd.ExecuteReader();

    while (sdr.Read())
    {
        dtDate_Ordered = (DateTime)sdr["dateordered"];
        dtDate_Required = (DateTime)sdr["daterequired"];
        dtDate_Received = (DateTime)sdr["daterecv"];
        stringComments = (string)sdr["comments"];
    }
}
catch (Exception Ex)
{
    Class_Connection.cnn.Close();
    throw Ex;
}

Class_Connection.cnn.Close();

RDI_Date_Ordered.SelectedDate = dtDate_Ordered;
RDI_Date_Required.SelectedDate = dtDate_Required;
RDI_Date_Received.SelectedDate = dtDate_Received;

I would like to be able to handle the null value, before the exception handler catches it.

7
  • 1
    why not do something like stringComments = (sdr["comments"] = DbNull.Value ? string.Empty : dr.GetString(dr.GetOrdinal("comments"))); Commented Jul 16, 2014 at 20:28
  • @RowlandShaw I tried that. I got and error that I couldn't resolve the symbols for Db.Null and dr Commented Jul 16, 2014 at 20:35
  • Sorry, dodgy shift key, should read DBNull.Value Commented Jul 16, 2014 at 20:36
  • 2
    needs to be == to do the inline comparison Commented Jul 16, 2014 at 20:51
  • 1
    @RowlandShaw I think I got that to work with a string, how would I do it with a datetime type? Commented Jul 16, 2014 at 21:05

2 Answers 2

1

Redefine your Datetimes at the top to be nullable, e.g.

private DateTime? dtDate_Ordered;

then when you're assigning them from the reader null won't be a problem.

if(sdr["dateordered"]==DbNull.Value)
    dtDate_Ordered=null
else
    dtDate_Ordered=sdr.GetDateTime(sdr.GetOrdinal("dateordered"))
Sign up to request clarification or add additional context in comments.

Comments

1

Before type casting the values check each to make sure they're not null.

if( sdr["dateordered"] != null)
    dtDate_Ordered = (DateTime)sdr["dateordered"];

if( sdr["daterequired"] != null)
    dtDate_Required = (DateTime)sdr["daterequired"];

if( sdr["daterecv"] != null)
    dtDate_Received = (DateTime)sdr["daterecv"];

stringComments = ( sdr["comments"] == null)? "" : (string)sdr["comments"];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.