使用asp.net交替的html表行背景颜色

时间:2014-01-29 12:54:12

标签: c# html asp.net

我正在使用c#asp.net从数据库中检索数据。我不想在填充数据时使用Gridview,而是使用html表。我以这种方式成功地从数据库中检索了数据。

这是HTML代码

<table class="listing" cellpadding="0" cellspacing="0">
    <tr>
        <th>Lastname</th>
        <th>Firstname</th>
        <th>Middlename</th>
        <th>Age</th>
    </tr>

    <%=LoadHtmlTableCustomerData()%> 

 </table>

背后的代码。

public string LoadHtmlTableCustomerData()
{
    SqlConnection connection = new System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings["dbaseconnection"].ConnectionString);
    string HTML = "";
    try
    {
        SqlCommand command = new SqlCommand("SELECT  * FROM tbl_Customers", connection);
        connection.Open();
        SqlDataReader dr = command.ExecuteReader();
        if (dr.HasRows)
        {
            while (dr.Read())
            {
                string lastname = dr[1].ToString();
                string firstname = dr[2].ToString();
                string middlename = dr[3].ToString();
                string age = dr[4].ToString();

                HTML += "<tr><td>" + lastname + "</td><td>" + firstname + "</td><td>" + middlename + "</td><td>" + age + "</td></tr>";
            }
        }
    }
    catch (Exception) { }
    finally { connection.Close(); }
    return HTML;
}

如何实现?例子我想把第一个tr标签放在tr class ='white-row';第二个标签tr class =“green-row”..等等

只是交替的行背景颜色。请帮帮我。

2 个答案:

答案 0 :(得分:3)

对于现代浏览器,您可以使用CSS。

tr:nth-child(odd) { background-color: #000; }
tr:nth-child(even) { background-color: #fff; }

http://davidwalsh.name/css-tables-css3-alternate-row-colors

答案 1 :(得分:1)

public string LoadHtmlTableCustomerData()
{
    SqlConnection connection = new System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings["dbaseconnection"].ConnectionString);
    string HTML = "";
    try
    {
        SqlCommand command = new SqlCommand("SELECT  * FROM tbl_Customers", connection);
        connection.Open();
        SqlDataReader dr = command.ExecuteReader();
        if (dr.HasRows)
        {
            int count = 0;
            while (dr.Read())
            {
                string lastname = dr[1].ToString();
                string firstname = dr[2].ToString();
                string middlename = dr[3].ToString();
                string age = dr[4].ToString();

                HTML += "<tr class=\"" + (count % 2 == 0 ? "white-row" : "green-row") + "\"><td>" + lastname + "</td><td>" + firstname + "</td><td>" + middlename + "</td><td>" + age + "</td></tr>";
                count++;
            }
        }
    }
    catch (Exception) { }
    finally { connection.Close(); }
    return HTML;
}