0

I try to read the result of the query and discover if some of the columns is empty This is a way I started:

SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
    rdr["ColumnName"]; // how do I know if it has a value or empty
}

I thought to do :

dr[4].ToString() == String.Empty

It makes a needed work, but I don`t like this (it is a hack rather than solution) can you advise me how do I do it correctly and elegantly?

2
  • when you say "empty", does that include nulls? are you only concerned about var/char type columns? Commented Apr 21, 2014 at 14:55
  • @attila 1.NO 2.I am interested in int type columns Commented Apr 21, 2014 at 14:59

3 Answers 3

3

Empty does not exists for int values and what is correct when working with databases is use Null which is the only true "Empty".

SqlDataReader rdr = cmd.ExecuteReader();
int colIndex = read.GetOrdinal("MyColumnName");

while (rdr.Read())
{
    // [true | false] your validation goes here!; 

    if (rdr.IsDBNull(colIndex)){
       //value is  null
    }
}

Please note that if you want use 0, "" or 1/1/1900 as empty values those will require a custom treatment.

Sign up to request clarification or add additional context in comments.

Comments

1

This is how I do it

string UserInitialssql = rdr.IsDBNull(2) ? String.Empty : rdr.GetString(2);

If it is Int

Int32? i = rdr.IsDBNull(2) ? (Int32?)null : rdr2.GetInt32(2);

Comments

0

Another possibility is to use nullable types. e.g.:

SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
    int? someNumber = rdr["ColumnName"] as int?;
    if (someNumber == null)
        // was NULL in database
    else 
       // use  someNumber.Value   to get int
}

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.