“不存在数据时读取尝试无效”错误

Joh*_*nes 1 c# code-behind

我有这个代码块:

using (SqlConnection con2 = new SqlConnection(str2))
{
    using (SqlCommand cmd2 = new SqlCommand(@"SELECT * FROM VW_MOS_DPL_AccountValidation WHERE CUST_NUM = @CNum", con2))
    {
        con2.Open();

        cmd2.Parameters.AddWithValue("@CNum", TBAccountNum.Text);

        using (SqlDataReader DT2 = cmd2.ExecuteReader())
        {
            // If the SQL returns any records, process the info
            if (DT2.HasRows)
            {
                // If there's a BusinessID (aka Business Type), fill it in
                string BizID = (DT2["Business_ID"].ToString());
                if (!string.IsNullOrEmpty(BizID))
                {
                    DDLBustype.SelectedValue = BizID;
                }
            }
        }
        con2.Close();
    }
}
Run Code Online (Sandbox Code Playgroud)

当它到达线路时

string BizID = (DT2["Business_ID"].ToString());
Run Code Online (Sandbox Code Playgroud)

它抛出一个错误:

不存在数据时尝试读取无效。

if (DT2.HasRows)如果没有数据,为什么会过去?

Ste*_*eve 5

你需要打电话

if(DT2.Read()) 
 ....
Run Code Online (Sandbox Code Playgroud)

在继续从 DataReader 读取数据之前。

HasRows告诉你只有SqlDataReader中包含的数据,但SqlDataReader的载荷从连接时间的一个记录。因此,每次从 SqlDataReader 中提取数据的尝试之前都应该调用Read以将 SqlDataReader 定位在通过连接返回的第一条记录上。

而且,因为如果调用能够读取记录,则 Read 方法返回 true,所以您可以用类似这样的内容替换对 HasRows 的调用

    using (SqlDataReader DT2 = cmd2.ExecuteReader())
    {
        // If the SQL returns any records, process the info
        while(DT2.Read())
        {
            // If there's a BusinessID (aka Business Type), fill it in
            string BizID = (DT2["Business_ID"].ToString());
            if (!string.IsNullOrEmpty(BizID))
            {
                DDLBustype.SelectedValue = BizID;
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

顺便说一句,如果 BusinessID 可能有一个 NULL 那么你需要一个不同的测试来避免异常问题

int bizColIndex = DT2.GetOrdinal("Business_ID");
string BizID = (DT2.IsDBNull(bizColIndex) ? string.Empty : DT2.GetString(bizColIndex));
if (!string.IsNullOrEmpty(BizID))
{
    DDLBustype.SelectedValue = BizID;
}
Run Code Online (Sandbox Code Playgroud)