|
DataGrid - Relative Conditional Formatting
Published: 11/17/2008 |
|
Conditional formatting in Excel is a powerful way to change the contents or format of a cell based on the values of other cells relative to it. What if you wanted to extend that to a databound grid in .NET? Here's a simple example I whipped up in response to a post over on VBCity:
C# (WinForms):
private void dgElementTypes_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (e.ColumnIndex == 0)
{
if (e.RowIndex > 0)
{
if (e.Value != null)
{
DataGridViewCell previousCell = dgElementTypes.Rows[e.RowIndex - 1].Cells[e.ColumnIndex];
if (previousCell.Value != null)
{
if (e.Value.ToString() == previousCell.Value.ToString())
e.Value = "";
}
}
}
}
}
This code takes advantage of the CellFormatting event of the control to check the value of the same cell in a previous row to block out a repeated value - so that a value in a sorted list only appears once and is blanked out in subsequent cells until the value changes.
Here's the same example from the Web:
C# (ASP.NET):
protected void Page_Load(object sender, EventArgs e)
{
DataSet ds = new DataSet("test");
ds.Tables.Add("test");
ds.Tables[0].Columns.Add("test", typeof(string));
ds.Tables[0].Rows.Add(new string[] { "Hello World!" });
ds.Tables[0].Rows.Add(new string[] { "Hello World!" });
ds.Tables[0].Rows.Add(new string[] { "Hello World!" });
this.GridView1.DataSource = ds;
this.GridView1.DataMember = "test";
this.GridView1.DataBind();
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowIndex > 0)
{
string thisValue = GetFirstCellValue(e.Row.RowIndex);
string previousValue = GetFirstCellValue(e.Row.RowIndex - 1);
if (thisValue == previousValue)
e.Row.Cells[0].Text = "\'\'";
}
}
private string GetFirstCellValue(int RowIndex)
{
DataTable dt = ((DataSet)this.GridView1.DataSource).Tables[0];
object temp = dt.Rows[RowIndex].ItemArray[0];
if (temp == null)
return "";
else
return temp.ToString();
}
This example is slightly different - there's no CellFormatting event of the Web version of the control, so here we use the RowDataBound event of the control to change the value of the cell text before it is added to the grid.
Questions or Comments? .
VB to C# and C# to VB translation provided by Instant C# and Instant VB.