Thursday, February 14, 2008

How to Highlight a row in DataGrid

In this post I will discuss about how to highlight a row in datagrid when mouse moves over a row, by using onmouseover and onmouseout javascript events.

Datagrid has two events, ItemCreated and ItemDataBound, which allow us to access the data items and create an event handler for the events. ItemCreated event is raised when an item in the datagrid control is created, while ItemDataBound event is raised after an item in the datagrid control is created.

In this example, I will work with the ItemDataBound event, adding handlers for onmouseover and onmouseout javascript events for each of the row in the datagrid.

As you can see from the code snippet below, a row will be highlighted when mouse over and switched to normal when mouse out.

private void dgRows_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
{
     ListItemType itemType;
     itemType = (ListItemType)e.Item.ItemType;

     if(itemType == ListItemType.Item || itemType == ListItemType.AlternatingItem)
     {
         e.Item.Attributes.Add("onmouseover", "this.style.backgroundColor = 'gray';");
         e.Item.Attributes.Add("onmouseout", "this.style.backgroundColor = '#FFFFFF';");
     }
}

That’s it. Cheers!

4 comments:

Dick Chiang on August 26, 2008 at 12:13 PM said...

Hi, which version of Visual Studio are you using? I'm on VS2005 and the only GridView event I see close to this is 'DataBound'. I don't see an 'ItemDataBound' event.

xiaoyu on August 26, 2008 at 1:52 PM said...

Yes. ItemDataBound event only exists in DataGrid (VS2003), For GridView, you can use RowDataBound event instead.

Thanks.

Anonymous said...

Amiable brief and this mail helped me alot in my college assignement. Thank you seeking your information.

Anonymous said...

Opulently I agree but I about the brief should prepare more info then it has.

 

Get paid for your opinions! Click on the banner above to join Planet Pulse. Its totally free to sign up, and you can earn UNLIMITED. Find out more by visiting PLANET PULSE.
Sign up for PayPal and start accepting credit card payments instantly. http://www.emailcashpro.com
July Code Blog Copyright © 2010 Blogger Template Designed by Bie Blogger Template