我有一个SqlDataReader
从中提取数据的。我正在尝试根据来自阅读器的数据向用户显示不同的消息。当我的 if 语句返回 true 时,当 if 语句返回 false 时,数据正确显示,我得到一个冗长的错误:
System.InvalidOperationException:不存在数据时尝试读取无效。 在 System.Data.SqlClient.SqlDataReader.TryReadColumn (Int32 i, Boolean setTimeout, Boolean allowPartiallyReadColumn) 在 System.Data.SqlClient
的 System.Data.SqlClient.SqlDataReader.CheckDataIsReady(Int32 columnIndex, 布尔 allowPartiallyReadColumn, 布尔 permitAsync, String methodName) 。
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();
}
}