Wednesday, July 22, 2009

Eliminate Duplicate records from the Grid View

Most of the time we need to delete duplicate entries from GridView, in this case we can delete it manually also or using onRowcreate also we can remove that .

Example
suppose Mr.Xyz has has more than 2 Account in Blogspot.com site and we want to show
in GridView Person and RelatedBlogs like this





and in this case we dont want to repeat Person name on each row.
- I have a data source

DataTable dtsource = new DataTable();

//Adding columns to datatable
dtsource.Columns.Add("Person");
dtsource.Columns.Add("Related Blog");

//Adding records to the datatable
dtsource.Rows.Add("kiran", "kirank.blog.com");
dtsource.Rows.Add("kiran", "webdevlopmenthelp");
dtsource.Rows.Add("kiran", "www.kiran.com");
dtsource.Rows.Add("mark", "mark.blog.com");
dtsource.Rows.Add("mark", "asp-net.blogspot.com");


put the below code in codebehind


private void GenerateUniqueData(int cellno)
{
//Logic for unique names

//Step 1:

string initialnamevalue = grdUniqueNames.Rows[0].Cells[cellno].Text;

//Step 2:

for (int i = 1; i < grdUniqueNames.Rows.Count; i++)
{

if (grdUniqueNames.Rows[i].Cells[cellno].Text == initialnamevalue)
grdUniqueNames.Rows[i].Cells[cellno].Text = string.Empty;
else
initialnamevalue = grdUniqueNames.Rows[i].Cells[cellno].Text;
}
}



on GridView define property OnRowCreated="GenerateUniqueData" it will search the record via cell and set the Person name as a empty or person name

8 comments:

  1. hi,

    some of my friends are sending me person mail in that it was written
    they are getting Error on Error on missing parameter cellno...

    friends here "cellno" means its a field name from databse , on which you want to do operation.

    change it as per you'r database field

    hope it will works

    ReplyDelete
  2. Hi Kiran,

    It does not work for me...

    On aspx page i declare as

    "asp's gridview OnRowCreated="GenerateUniqueData"

    In code behind:
    I declare the code u have mentioned.I replaced the parameter(int cellno) by columname which comes from my dataset .

    It gives below error:
    CS0123: No overload for 'GenerateUniqueData' matches delegate 'System.Web.UI.WebControls.GridViewRowEventHandler'

    ReplyDelete
    Replies
    1. thanks for comments.

      you need to create one overload called "GenerateUniqueData" and define the gridhandler on same.

      let me know in case of any issues.

      Delete
  3. sorry friends plz keep cellno as it is
    and instead of that plz change the
    Rows[0] value
    result from your query

    ReplyDelete
  4. Does not work, throws the error mentioned by Anonymous.

    ReplyDelete
    Replies
    1. Hi..

      May i know where exactly it get stuck? and what error message it get throws.

      Delete
  5. you save my life...:)))))))))))))
    thnx a lot.....

    ReplyDelete
    Replies
    1. Hi Piyumi,

      thanks for your comments.. let me know if you want any other help.

      Delete