C#使用while循环为SqlDataReader [关闭]

问题描述 投票:1回答:3

我正在尝试使用while循环修改数据读取器中的数据,以使用innerHtml将数据显示为网页上HTML表上的行。它适用于第一次迭代,但不会为其余数据重复迭代。

已检查数据读取器上是否存在所有数据,因此似乎与我的while循环代码有关

关于我做错了什么的任何建议?

string description = "placeholder";
string desc_mod;

query.InnerHtml += "<table class='list_format'>";

using (SqlDataReader productList = SQLHelper.ExecuteQuery(query1))
    if (productList.HasRows)
    {
        while (productList.Read())
            description = (string)productList["Description"];

        desc_mod = description.Substring(0, 30);
        query.InnerHtml += "<tr><td><div><p>" + desc_mod + "</p</div></td></tr>";
    }

query.InnerHtml += "</table>";
c# sql-server while-loop sqldatareader
3个回答
3
投票

您缺少一组花括号来分隔您的while块和您的使用块:

    string description = "placeholder";
    string desc_mod;
    query.InnerHtml += "<table class='list_format'>";
    using (SqlDataReader productList = SQLHelper.ExecuteQuery(query1)) {
        if (productList.HasRows){
            {
                while (productList.Read()) {
                    description = (string)productList["Description"];
                    desc_mod = description.Substring(0, 30);
                    query.InnerHtml += "<tr><td><div><p>" + desc_mod + "</p</div></td></tr>";
                }
            }
        }
    }
    query.InnerHtml += "</table>";

如果省略代码块上的大括号,例如qazxsw poi,qazxsw poi或qazxsw poi等,编译器将仅处理作为块的一部分紧随其后的行。


0
投票

缺少while语句的一些括号

using

0
投票

使用while循环和if

string description = "placeholder";
    string desc_mod;
    query.InnerHtml += "<table class='list_format'>";
    using (SqlDataReader productList = SQLHelper.ExecuteQuery(query1))
        if (productList.HasRows){
            {
                while (productList.Read())
                {
                    description = (string)productList["Description"];
                    desc_mod = description.Substring(0, 30);
                query.InnerHtml += "<tr><td><div><p>" + desc_mod + "</p</div></td></tr>";
                }
            }
        }
    query.InnerHtml += "</table>";
© www.soinside.com 2019 - 2024. All rights reserved.