Search code examples
c#t-sqlsqldatareaderis-empty

SqlDataReader - how to discover that column is empty


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?


Solution

  • 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.