Syed Salman Raza Zaidi
Syed Salman Raza Zaidi

Reputation: 2192

HTML table generation using C# List

I am having a List of class, and I am filtering it with List's Where clause. After filtering I am using foreach loop for generating HTML table.It is generating items twice, ie if list count(after filtering) is 5,its generating table rows 10 times. I have checked while debugging,its executing properly ie 4 times. This is my code, in my aspx I have a table control like this

<asp:Table ID="table1" runat="server" CssClass="table">
    <asp:TableRow ID="TableRow1" runat="server">
        <asp:TableCell ID="TableCell1" runat="server">Name</asp:TableCell>
        <asp:TableCell ID="TableCell2" runat="server">Age</asp:TableCell>
        <asp:TableCell ID="TableCell3" runat="server">Sex</asp:TableCell>
        <asp:TableCell ID="TableCell4" runat="server">City</asp:TableCell>
        <asp:TableCell ID="TableCell5" runat="server">Delete</asp:TableCell>
    </asp:TableRow>
</asp:Table>


//lstusers is the List of Users Class,which contains information of users.
foreach (var item in lstusers.Where(r => r.Name == "salman").ToList())
{


    var namecell = new TableCell();
    namecell.Text = item.Name;

    var agecell = new TableCell();
    agecell.Text = item.Age.ToString();

    var sexcell = new TableCell();
    sexcell.Text = item.Sex;

    var citycell = new TableCell();
    citycell.Text = item.City;

    var delcell = new TableCell();
    delcell.Text = "<a href='#' id='deluser' class='del DeleteBtn'></a>";

    var newRow = new TableRow();
    newRow.Cells.Add(namecell);
    newRow.Cells.Add(agecell);
    newRow.Cells.Add(sexcell);
    newRow.Cells.Add(citycell);
    newRow.Cells.Add(delcell);
    table1.Rows.Add(newRow);
}

Where I am doing wrong, I have also tried lstusers.Where(r =>r.Name== "salman") but same issue with that as well

Upvotes: 0

Views: 181

Answers (1)

SpiderCode
SpiderCode

Reputation: 10122

According to my point of view, you should first clear table rows and then insert new rows. add

table1.Rows.Clear(); before foreach loop.

Upvotes: 1

Related Questions