Conditional Databinding

ASP.NET data presentation controls, like GridView, Repeater, DataList, ListView, DetailsView or FormView, could be used to show data from database fast and easy, even without single line of ASP.NET server side code. But, sometimes raw data from database are not suitable for showing on web form directly. You could need additional formatting for date values, handle NULLs, change 0 and 1 to something more intuitive to your visitors, show warning if value is too high or just change styles like background color.

Let's say you want to change color of GridView's cell depending of value. For example, if cell value is larger than 10 then background color should be red. Using GridView RowDataBound event this task is simple. Here is the code:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
	// Check if row is data row, not header, footer etc.
	if (e.Row.RowType == DataControlRowType.DataRow)
	{
		// Get value of third column. Index is zero based, to
		// get text of third column we use Cells[2].Text
		int CellValue = Convert.ToInt32(e.Row.Cells[2].Text);
                // If value is greater of 10, change format
		if (CellValue > 10)
		{
			// Use this syntax to change format of complete row
			e.Row.BackColor = System.Drawing.Color.Yellow;
			// Use this syntax to change format of single cell
			e.Row.Cells[2].BackColor = System.Drawing.Color.Red;
		}
	}
}

Sometimes, it is easier to change data directly in markup code. Here is the syntax that changes 1 and 0 to “Yes” and “No” respectively:


<img alt="" src="<%# (Eval("ImageURL")==DBNull.Value ? "DefaultImage.jpg" : DataBinder.Eval(Container.DataItem, "ImageURL")) %>" />

Notice that this way is not recommended if you manipulate with large data. Single property like image name or “Yes” and “No” are just short strings. If you need to manipulate with pile of HTML then it could be very confusing and certainly hard to maintain to keep it in single code line as literals. Unlike classic ASP, ASP.NET data controls don't allow syntax like:

<% If Eval("SomeValue") = 1 Then %>
Some HTML
<% Else %>
Some other HTML
<% End If %>

Til next time …


Leave a Reply

Your email address will not be published. Required fields are marked *