来自SqlDataReader的数据不会显示在else语句中

时间:2013-10-17 13:40:37

标签: asp.net if-statement sqldatareader

我有SqlDataReader我正在提取数据。我正在尝试根据来自阅读器的数据向用户显示不同的消息。当我的if语句返回true时,if语句返回false时数据显示正确我得到一个冗长的错误:

  

System.InvalidOperationException:没有数据时读取的尝试无效   at System.Data.SqlClient.SqlDataReader.CheckDataIsReady(Int32 columnIndex,Boolean allowPartiallyReadColumn,Boolean permitAsync,String methodName)
  at System.Data.SqlClient.SqlDataReader.TryReadColumn(Int32 i,Boolean setTimeout,Boolean allowPartiallyReadColumn)at System.Data.SqlClient.SqlDataReader.GetValueInternal(Int32 i)
  在System.Data.SqlClient.SqlDataReader.GetValue(Int32 i)
  在System.Data.SqlClient.SqlDataReader.get_Item(String name)

这是我的代码:

protected void Page_Load(object sender, EventArgs e)
{
    MembershipUser user = Membership.GetUser();
    string key = user.ProviderUserKey.ToString();

    SqlConnection con = new SqlConnection(connectionString);
    SqlCommand cmd = new SqlCommand("usp_GetDetails", con);
    cmd.CommandType = CommandType.StoredProcedure;

    cmd.Parameters.AddWithValue("@UserKey", key);

    SqlDataReader reader;
    try
    {
        con.Open();
        reader = cmd.ExecuteReader();

        reader.Read();

        getBidNumber = reader["SelectedBid"].ToString();
        getCompanyName = reader["CompanyName"].ToString();
        getUserKey = reader["MembershipUserKey"].ToString();
        getMerchantKey = reader["MerchantKey"].ToString();
        getMerchantName = reader["MerchantName"].ToString();

        this.DataBind();

        if (getBidNumber != null)
        {
            lblBidSelected.Text = "Congratulations you have selected #" + getBidNumber + " from " + getCompanyName + ". Click here to review you bid details.";
        }

        else
        {
            lblNoBidSelected.Text = "You have not selected a processor. Please <a href='bids-visit.aspx?mkey=" + getMerchantKey + "'>click here</a> to review your bids.";
        }


    }
    catch (Exception err)
    {
        lblError.Text = "There was an error " + err;
    }
    finally
    {
        con.Close();
    }

}

5 个答案:

答案 0 :(得分:2)

我建议使用HasRows更易读的SqlDataReader属性,如下所示:

if (reader.HasRows) 
{
    while (reader.Read()) 
    {
        // Do your reading logic here
        getBidNumber = reader["SelectedBid"].ToString();
        getCompanyName = reader["CompanyName"].ToString();
        getUserKey = reader["MembershipUserKey"].ToString();
        getMerchantKey = reader["MerchantKey"].ToString();
        getMerchantName = reader["MerchantName"].ToString();
    }
}

注意:这使得阅读逻辑处理任何数据的原因或原因非常明显。

更新:

将您的if-else逻辑更改为:

if (!String.IsNullOrEmpty(getBidNumber))
{
    lblBidSelected.Text = "Congratulations you have selected #" + getBidNumber + " from " + getCompanyName + ". Click here to review you bid details.";
}
else
{
    lblNoBidSelected.Text = "You have not selected a processor. Please <a href='bids-visit.aspx?mkey=" + getMerchantKey + "'>click here</a> to review your bids.";
}

注意:string将初始化为空字符串,而不是null,ToString()将不返回null;因此,使用IsNullOrEmpty()方法检查值更符合您的方法。

答案 1 :(得分:0)

由于你在else内,这意味着:

reader==null -> getMerchantKey = reader["MerchantKey"].ToString()==null

- &GT;你得到错误

答案 2 :(得分:0)

问题不在else区块内。之前抛出异常,在这一行:

getBidNumber = reader["SelectedBid"].ToString();

它抛出的原因是因为对reader.Read()的调用没有产生任何结果。只有似乎问题出现在else块,因为如果对reader.Read()的调用成功if条件,则始终会测试true 。你真正想要的是这样的代码:

if (reader.Read())
{
    getBidNumber = reader["SelectedBid"].ToString();
    getCompanyName = reader["CompanyName"].ToString();

    lblBidSelected.Text = "Congratulations you have selected # ... "
}
else
{
    //You'll need to change your error message, because the merchant key is unknown
    blNoBidSelected.Text = "You have not selected a processor. ... "
}

答案 3 :(得分:0)

您在到达if语句之前收到此错误可能是因为您的查询没有返回任何行。在继续之前检查reader.Read()返回值。

答案 4 :(得分:0)

首先像这样初始化

string getBidNumber =null;

何时进行字符串转换检查阅读器[“SelectedBid”]是否为空。

if(reader["SelectedBid"] !=null)
{
getBidNumber = reader["SelectedBid"].ToString();
}

其余代码全部相同。祝你好运