System.IndexOutOfRangeException on SQLDataReader Value Using C#

烂漫一生 提交于 2020-01-24 10:03:35

问题


I have a SQLDataReader that returns three integers. However, there are occasions when two of the integers will return null values.

To get round this I wrote the following:

int shoppingCartHeadID = 0;
int billID = 0;
int delID = 0;

conn.Open();
reader = comm.ExecuteReader();
if (reader.Read())
{
       shoppingCartHeadID = Convert.ToInt32(reader["shoppingCartHeadID"]);

       if (!reader.IsDBNull(billID))
       {
            billID = Convert.ToInt32(reader["billID"]);
       }

       if (!reader.IsDBNull(delID))
       {
            delID = Convert.ToInt32(reader["delID"]);
       }                
}
reader.Close();

Unfortunately I'm still getting the error message. Any suggestions?

PS I also tried this with no luck

if (reader["billID"] != null)


回答1:


I would try to access by index instead of column name, just in case you are passing a not existing column name.

Also, make sure you wrap your reader with a using block so in any case even if there is an exception your reader will be properly closed and disposed, for example in this way:

...
using(var reader = comm.ExecuteReader())
{
    if (reader.Read())
    {
           shoppingCartHeadID = Convert.ToInt32(reader[0]);

           if (!reader.IsDBNull(1))
           {
                billID = Convert.ToInt32(reader[1]);
           }

           if (!reader.IsDBNull(2))
           {
                delID = Convert.ToInt32(reader[2]);
           }
    }
}



回答2:


Use GetXXXX(colIndex) method.

if (!reader.IsDBNull(0)) // I presume that billid at 0 ordinal  
 {
    billID = reader.GetInt32(0);
 }
if (!reader.IsDBNull(1)) // I presume that delId at 1 ordinal
 {
    delID = reader.GetInt32(1);
 }  


来源:https://stackoverflow.com/questions/7711807/system-indexoutofrangeexception-on-sqldatareader-value-using-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!