how to check if a datareader is null or empty

前端 未结 12 1704
谎友^
谎友^ 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:15
    if (myReader.HasRows) //The key Word is **.HasRows**
    
    {
    
        ltlAdditional.Text = "Contains data";
    
    }
    
    else
    
    {   
    
        ltlAdditional.Text = "Is null Or Empty";
    
    }
    
    0 讨论(0)
  • 2020-12-24 02:23

    I also use OleDbDataReader.IsDBNull()

    if ( myReader.IsDBNull(colNum) ) { retrievedValue = ""; }
    else { retrievedValue = myReader.GetString(colNum); }
    
    0 讨论(0)
  • 2020-12-24 02:27

    In addition to the suggestions given, you can do this directly from your query like this -

    SELECT ISNULL([Additional], -1) AS [Additional]
    

    This way you can write the condition to check whether the field value is < 0 or >= 0.

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

    This is the correct and tested solution

    if (myReader.Read())
    {
    
        ltlAdditional.Text = "Contains data";
    }
    else
    {   
        ltlAdditional.Text = "Is null";
    }
    
    0 讨论(0)
  • 2020-12-24 02:31

    I also experiencing this kind of problem but mine, i'm using DbDataReader as my generic reader (for SQL, Oracle, OleDb, etc.). If using DataTable, DataTable has this method:

    DataTable dt = new DataTable();
    dt.Rows[0].Table.Columns.Contains("SampleColumn");
    

    using this I can determine if that column is existing in the result set that my query has. I'm also looking if DbDataReader has this capability.

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

    First of all, you probably want to check for a DBNull not a regular Null.

    Or you could look at the IsDBNull method

    0 讨论(0)
提交回复
热议问题