Вопрос

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?

Это было полезно?

Решение

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.

Другие советы

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);

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
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top