显示div中SQL查询返回的所有行

时间:2011-03-30 18:44:52

标签: c# asp.net sql innerhtml

我正在尝试使用div将我的SQL查询结果输出到InnerHTML。但我不能得到多个记录。如何制作以便我的所有记录都显示在DIV中?在我的页面上,DIV包含在UpdatePanel中,即使查询返回多行,我也只会显示1行。

string sql = "Select * From Events";
SqlCommand command = new SqlCommand(sql, conn);
command.CommandType = CommandType.Text;
conn.Open();
reader = command.ExecuteReader();
while (reader.Read())
{
    divout1.InnerHtml += "Name: " + reader["Name"].ToString() + "<br />" +
        "Date: " + reader["Date"].ToString() + "<br />" +
        "Location: " + reader["Location"].ToString() + "<br />";
    divout.Visible = true;
}

5 个答案:

答案 0 :(得分:1)

为什么不使用StringBuilder来构建你的sql,然后输出StringBuilder的内容:

StringBuilder sb = new StringBuilder(1024);
string sql = "Select * From Events";
SqlCommand command = new SqlCommand(sql, conn);
command.CommandType = CommandType.Text;
conn.Open();
reader = command.ExecuteReader();

while (reader.Read())
{
    sb.AppendLine("Name: " + reader["Name"].ToString() + "<br />" +
        "Date: " + reader["Date"].ToString() + "<br />" +
        "Location: " + reader["Location"].ToString() + "<br />");
}

if(sb.Length > 0) {
    divout.InnerHtml = sb.ToString();
    divout.Visible = true;
}

答案 1 :(得分:1)

为什么不尝试这样的事情,可能会在InnerHtml中连接起来搞砸了什么。还要确保你真的有一排。

    var sb = new StringBuilder();  
    var formatString = "Name: {0} <br />Date: {1}<br />Location: {2}<br />"; 
    while (reader.Read())
    {
        sb.AppendFormat(formatString, reader["Name"].ToString(), reader["Date"].ToString(), reader["Location"].ToString());
    }
    divout1.InnerHtml = sb.Tostring();
    divout1.Visible = true;

答案 2 :(得分:1)

嗯,初看起来,除非你的查询只返回一行,否则它应该得到div上的所有数据。

尝试在while语句的最后一个括号上设置一个断点,看看你的div在第一次迭代后会发生什么。

换句话说,尝试将div从updatepanel中删除以查看附加内容?

答案 3 :(得分:0)

尝试:

            string sql = "Select * From Events";
            SqlCommand command = new SqlCommand(sql, conn);
            command.CommandType = CommandType.Text;
            conn.Open();
            reader = command.ExecuteReader();
            string s = string.Empty;
            while (reader.Read())
            {
                s += "Name: " + reader["Name"].ToString() + "<br />" +
                    "Date: " + reader["Date"].ToString() + "<br />" +
                    "Location: " + reader["Location"].ToString() + "<br />";

            }
            divout1.innerHtml = s;
            divout1.Visible = true;

答案 4 :(得分:0)

您应该对来自数据库的字符串进行编码,因为您直接将其作为原始HTML输出。

divout1.InnerHtml += "Name: " + Server.HtmlEncode(reader["Name"].ToString()) + "<br />" 
                   + "Date: " + Server.HtmlEncode(reader["Date"].ToString()) + "<br />"  
                   + "Location: " + Server.HtmlEncode(reader["Location"].ToString()) + "<br />";

请参阅HttpServerUtility.HtmlEncode