移除GridView中的重复项

1. The HTML Markup

  <div>
            <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White">
                <Columns>
                    <asp:BoundField DataField="Id" HeaderText="Id" ItemStyle-Width="30" />
                    <asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="150" />
                    <asp:BoundField DataField="City" HeaderText="City" ItemStyle-Width="150" />
                </Columns>
            </asp:GridView>
            <br />
            <asp:Button ID="btnRemove" runat="server" Text="Remove Duplicates" OnClick="btnRemove_Click" />
        </div>

 2. 绑定GridView的方法

 public void BindGridview()
        {
            DataTable dt = new DataTable();
            dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id"), new DataColumn("Name"), new DataColumn("City") });
            dt.Rows.Add(1, "John Hammond", "United States");
            dt.Rows.Add(1, "John Hammond", "United States");
            dt.Rows.Add(2, "Mudassar Khan", "India");
            dt.Rows.Add(2, "Mudassar Khan", "India");
            dt.Rows.Add(3, "Suzanne Mathews", "France");
            dt.Rows.Add(3, "Suzanne Mathews", "France");
            dt.Rows.Add(3, "Suzanne Mathews", "France");
            dt.Rows.Add(4, "Robert Schidner", "Russia");
            dt.Rows.Add(4, "Robert Schidner", "Russia");
            dt.Rows.Add(4, "Robert Schidner", "Russia");
            dt.Rows.Add(4, "Robert Schidner", "Russia");

            ViewState["dt"] = dt;
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }
       

 3. 移除重复项的方法

 public void RemoveDuplicateReords()
        {
            DataTable dt = (DataTable)ViewState["dt"];
            dt = dt.DefaultView.ToTable(true, "Id", "Name", "City");
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }

 更多的详细信息,请访问下面的链接

http://www.aspsnippets.com/Articles/Remove-Delete-Duplicate-Rows-Records-from-DataTable-using-C-and-VBNet.aspx

 

posted @ 2015-02-03 18:57  songxia777  阅读(368)  评论(0编辑  收藏  举报