Friday, July 28, 2006

Highlight rows in a DataGrid

Here is another useful piece of code which can be helpful for novice programmers.

DataGrid is a very nice tool to present the data. It is quite easy and once you start using that, I am sure, anybody would enjoy using that control. We can bind a grid to a dataset in just two steps.

  1. Assign the DataSource property of the grid to a DataObject. The DataObject can be anything from a DataSet to an array.

  2. Call the DataBind() method to bind the data.

We can do further processing in the control in its ItemDataBound event.

Once you have bound the data, the ItemDataBound even can be used to do furthur processing.

In this example I present how to mark certain rows in a DataGrid based on some data. Here I use the Employees table in the Northwind database. I populate a grid with data and mark the Employees whose city is "Seattle"

The Code...

void Page_Load(object sender, EventArgs e)
DataGrid1.DataSource = GetData();

void DataGrid1_ItemDataBound(object sender, DataGridItemEventArgs e)
if(e.Item.ItemType == ListItemType.Item e.Item.ItemType == ListItemType.AlternatingItem)
if (e.Item.Cells[4].Text == "Seattle") // Cell4 Contains the City
e.Item.CssClass = "Hilite";

I have not included the code for creating the DataSet. The HTML has also not been inlcuded. It contains a DataGrid

See also
  1. Export DataGrid to Excel
  2. Showing Checkboxes in Grid
  3. Create Serial# column in Datagrid/DataList


    Post a Comment

    << Home