Sunday, July 4, 2010

How to hide duplicate Column Entries GridView VS2008 using c#

The Code below will hide values of textbox and label controls with the same ID in a gridview, you should be able to modify the code easily enough to support other controls. This does however mean that you have to use TemplateFields not basic BoundFields. For example if you have a Template field and inside it you have a textbox called txtName and a Phone number field called txtPhone, you specify HideDuplicatesInColumns to "txtName,txtPhone" for example:

<cus:GridView2 runat="server" ID="grdTrainMeNonSuperSet" AutoGenerateColumns="false"
HideDuplicatesInColumns="lblExerciseShort,lblMuscleGroup" GridLines="Horizontal"
OnRowCommand="grdTrainMeNonSuperSet_RowCommand">

Before you do this you need to add this class to you appcode folder, and in the your asp.net page add a reference to it.

Example of the Reference
<%@ Register Namespace="ST.Web.Controls" TagPrefix="cus" % >



The Class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using System.Web.Configuration;
using System.Web.UI;

namespace ST.Web.Controls
{
///
/// Summary description for GridView2
///
public class GridView2 : GridView
{
public GridView2()
: base()
{

}

protected override void OnDataBound(EventArgs e)
{
base.OnDataBound(e);
}

string hideDuplicatesInColumns = string.Empty;HideDuplicatesInColumns
string[] columnsToHideDups;

public string
{
set
{
hideDuplicatesInColumns = value;
columnsToHideDups = hideDuplicatesInColumns.Split(Convert.ToChar(","));
}
get
{
return hideDuplicatesInColumns;
}
}

private int ConvertToInt(string value)
{
return Convert.ToInt32(value);
}

Dictionary watchList = new Dictionary();
protected override void OnRowDataBound(GridViewRowEventArgs e)
{
if (columnsToHideDups != null)
{
//Hide all the duplicate values in based on the selected settings
foreach (string c in columnsToHideDups)
{
Control cntrl = e.Row.FindControl(c);

string val = string.Empty;
string id = string.Empty;
string key = string.Empty;
if (cntrl is TextBox)
{
val = ((TextBox)cntrl).Text;
id = ((TextBox)cntrl).ID;
key = string.Format("{0}", id);
if (watchList.ContainsKey(key) && watchList[key] == val)
{
((TextBox)cntrl).Text = String.Empty;
continue;
}
else
{
watchList.Add(key, val);
watchList[key] = val;
}
}
if (cntrl is Label)
{
val = ((Label)cntrl).Text;
id = ((Label)cntrl).ID;
key = string.Format("{0}", id);
if (watchList.ContainsKey(key) && watchList[key] == val)
{
((Label)cntrl).Text = String.Empty;
continue;
}
else
{
watchList[key] = val;
}
}

}
}
base.OnRowDataBound(e);
}

protected override void OnRowCreated(GridViewRowEventArgs e)
{
base.OnRowCreated(e);
}
}
}