简体   繁体   中英

How to add “li” to “ul” tag with C#

i am trying to get some names from Sql database and append them as "li" in to pre-created "ul" with the code below. i am getting "System.Data.Common.DataRecordInternal" instead my datas in Sql what could be the problem?

also with this code i cannot take first item in SQL. i mean totaly i have 9 item in Sql however i get only 8 "System.Data.Common.DataRecordInternal".

the code:

HTML

<div class="modal-body" style="width: 1000px;">
    <ul class="list-group" runat="server" id="A3List">
    </ul>
</div>

C#

protected void loadEval_ServerClick(object sender, EventArgs e)
{
    SqlCommand comd = new SqlCommand("select name from A3_Coaching", con.connection());
    SqlDataReader dr = comd.ExecuteReader();

    while (dr.Read())
    {
        foreach (var r in dr)
        {
            HtmlGenericControl li = new HtmlGenericControl("li");
            A3List.Controls.Add(li);
            li.InnerHtml = r.ToString();
        }
    }
}

You need to read the actual column name from the data reader not just do a.ToString which will print out the underlying type's name. You don't need the extra foreach also, the while on the DataReader is your loop. Try the below.

protected void loadEval_ServerClick(object sender, EventArgs e)
{
    SqlCommand comd = new SqlCommand("select name from A3_Coaching", con.connection());
    SqlDataReader dr = comd.ExecuteReader();

    while (dr.Read())
    {
        HtmlGenericControl li = new HtmlGenericControl("li");
        A3List.Controls.Add(li);
        li.InnerHtml = dr["name"];        
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM