简体   繁体   中英

Looping through HTML controls - ASP.NET

I have some rows that runs on server and I want to make some of them bold according to some conditions. How can I loop through the controls. My rows seems like this:

<tr id="row1" runat="server"></tr>
<tr id="row2" runat="server"></tr>
<tr id="row3" runat="server"></tr>

Try something like this:

Markup

<table id="table1" runat="server">
    <tr id="row1" runat="server"><td>cell1</td></tr>
    <tr id="row2" runat="server"><td>cell2</td></tr>
    <tr id="row3" runat="server"><td>cell3</td></tr>    
</table>

Code

using System.Web.UI.HtmlControls;

...

foreach (HtmlTableRow row in table1.Rows)
{
    row.Style.Add("font-weight", "bold");
}

Hope this helps.

You should use a Repeater to output the content. This has the ability to change rows based on AlternatingItemTemplate and ItemTemplate .

 <asp:Repeater ID="repeater" runat="server" 
    onitemdatabound="repeater_ItemDataBound">
    <HeaderTemplate>
       <table>
    </HeaderTemplate>
    <ItemTemplate>
        <tr runat="server" id="row" class="odd">
           <td><%# Container.DataItem %></td>
        </tr>
    </ItemTemplate>
    <AlternatingItemTemplate>
        <tr runat="server" id="row" class="even">
           <td><%# Container.DataItem%></td>
        </tr>
    </AlternatingItemTemplate>
    <FooterTemplate>
       </table>
    </FooterTemplate>
</asp:Repeater>

You can also hook the ItemDataBound events and customize look and feel as the data is written.

protected void repeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item ||
        e.Item.ItemType == ListItemType.AlternatingItem)
    {
        var data = e.Item.DataItem;
        var index = e.Item.ItemIndex;

        var row = e.Item.FindControl("row");

        // do something with row control
    }
}

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