how to check if a datareader is null or empty

前端 未结 12 1745
谎友^
谎友^ 2020-12-24 01:52

I have a datareader that return a lsit of records from a sql server database. I have a field in the database called "Additional". This field is 50% of the time emp

相关标签:
12条回答
  • 2020-12-24 02:36

    I haven't used DataReaders for 3+ years, so I wanted to confirm my memory and found this. Anyway, for anyone who happens upon this post like I did and wants a method to test IsDBNull using the column name instead of ordinal number, and you are using VS 2008+ (& .NET 3.5 I think), you can write an extension method so that you can pass the column name in:

    public static class DataReaderExtensions
    {
        public static bool IsDBNull( this IDataReader dataReader, string columnName )
        {
            return dataReader[columnName] == DBNull.Value;
        }
    }
    

    Kevin

    0 讨论(0)
  • 2020-12-24 02:36

    AMG - Sorry all, was having a blond moment. The field "Additional" was added to the database after I had initially designed the database.

    I updated all my code to use this new field, however I forgot to update the actual datareader code that was making the call to select the database fields, therefore it wasn't calling "Additional"

    0 讨论(0)
  • 2020-12-24 02:37

    @Joe Philllips

    SQlDataReader.IsDBNull(int index) requires the ordinal number of the column. Is there a way to check for nulls using Column Name, and not it's Ordinal Number?

    0 讨论(0)
  • 2020-12-24 02:37

    This

    Example:

    objCar.StrDescription = (objSqlDataReader["fieldDescription"].GetType() != typeof(DBNull)) ? (String)objSqlDataReader["fieldDescription"] : "";
    
    0 讨论(0)
  • 2020-12-24 02:39
    if (myReader["Additional"] != DBNull.Value)
    {
        ltlAdditional.Text = "contains data";
    }
    else
    {
         ltlAdditional.Text = "is null";
    }
    
    0 讨论(0)
  • 2020-12-24 02:39

    Try this simpler equivalent syntax:

    ltlAdditional.Text = (myReader["Additional"] == DBNull.Value) ? "is null" : "contains data";
    
    0 讨论(0)
提交回复
热议问题