首页 > 解决方案 > SqlDataReader 为什么只返回第一行值?

问题描述

我需要返回列 Test 中的所有值,但不知何故只返回第一行值...

我试图添加 dr2.NextResult(); 到代码,但它没有帮助

SqlCommand command = conn.CreateCommand();
command.CommandText = "select Test from PrescTest ";

conn.Open();
command.ExecuteNonQuery();

SqlDataReader dr2 = command.ExecuteReader();
try
{
    while (dr2.Read())
    {
        // get the results of column "Test"
        string Tests = (string)dr2["Test"].ToString();
        TextBox15.Text = Tests +" ";
    }
    conn.Close();
}
catch (SqlException sqlexception)
{
    Response.Write("ERROR ::" + sqlexception.Message);
}
catch (Exception ex)
{
    Response.Write("ERROR ::" + ex.Message);
}
finally
{
    conn.Close();
}

标签: c#asp.net

解决方案


您被分配了值并删除了文本框的先前值。试试这个:

while (dr2.Read())
{
    // get the results of column "Test"
    string Tests = dr2["Test"].ToString();
    TextBox15.Text += Tests +" ";
}

推荐阅读