Let’s start with an example.
Suppose a person Mr. XYZ has purchased two or three houses in three different places. Another person Mr. ABC has more than one house. Now the requirement is to display the information of those persons along with the house addresses with the constraint that the names should not be repeated. This example will demonstrate how to resolve such problems.
Straight to the Program
In the program, I have a data source (which is a datatable) as shown below:
DataTable dtsource = new DataTable();
dtsource.Rows.Add( "Name1", "Address11");
As can be observed that the names are repeated, nevertheless, the addresses are unique. I have taken two
GridViews, the first which will show the information having duplicate values while the second is without duplicates. In the pageload event, I am binding the respective grids with the datasource Next, the task is to remove the duplicate rows. A small two step algorithm is running behind that:
Algorithm: Remove duplicate data
Step 1: Store the first row's , first cells content
Step 2: Loop through the entire grid from the 2nd row till the end
and check if the Name column's value is same or not.
If it is same, then replace the value with empty string
else continue with the new value. The above process will repeat itself
So let’s portray the above algorithm into the picture.
private void GenerateUniqueData(int cellno)
string initialnamevalue = grdUniqueNames.Rows.Cells[cellno].Text;
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;
initialnamevalue = grdUniqueNames.Rows[i].Cells[cellno].Text;
GenerateUniqueData does the necessary function. It accepts only one parameter,
CellNo which is used to determine upon which cell, the algorithm needs to work. The calling function
GenerateUniqueData(0) passes the values as
0 indicating that the first column’s data should be unique.
Though simple and not needing much explanation, since it’s a real time scenario, I thought of sharing this small and simple example with others.
- 24th May, 2009: Initial post