日期:2014-05-19  浏览次数:20787 次

datareader抛出数值为空的异常,请教
以下代码在运行时,如果选择的时间段内没有数据,但是read()的返回值仍是true,然后抛出一个数据为空的异常。请教如何解决。

string   sql   =   "select   sum(money)   as   total   from   t_operlog   where   operid= ' "+qiantaiCombobox.SelectedValue+
                                " '   and     opertime   between   ' "+beginDate.Value+ " '   and   ' "+endDate.Value+ " '   ";
                        try
                        {
                                SqlConnection   conn   =   getConnection();
                                SqlCommand   cmd   =   conn.CreateCommand();
                                cmd.CommandText   =   sql;
                                SqlDataReader   reader   =   cmd.ExecuteReader();
                                if(reader.Read())
                                {

                              MessageBox.Show( "!!! ");
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~这一句在选择的时间段内没有数据的时候仍会执行,说明返回值应该是true
                                  //label30.Text   =   reader.GetDouble(0).ToString();
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~但是如果执行这一句就抛出异常。
                                     
                                }
                             
                                reader.Close();
                                conn.Close();

                        }
                        catch   (Exception   ex)
                        {
                                MessageBox.Show( "Error: "   +   ex.Message,   "Errors ",   MessageBoxButtons.OK,   MessageBoxIcon.Error);
                        }

------解决方案--------------------
是不是你第0行就没有查询到数据,你把sql语句跟踪出来,到查询分析器