0

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

4
  • You could use the GridView or Repeater controller and do this alot easier with databinding. Commented Apr 11, 2014 at 8:58
  • Yes but I have to use this Commented Apr 11, 2014 at 9:01
  • Where are you calling this code? I mean is it in Page_Load event or in a button click event or where? Can you show that code to us? Commented Apr 11, 2014 at 9:07
  • Yes on page load I have checked for condition it its not post back Commented Apr 11, 2014 at 9:12

1 Answer 1

1

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

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.