Sunday, October 21, 2012

Highlight gridview row on mouse over in asp net web page: Adding effects to the gridview control


Programmers heavily use the asp.net gridview control. Adding some effects to the gridview will change the appearance so that user interactivity increases. One of such effects is highlighting the gridview row on mouseover. With this short background let's go for the design markup of the example gridview.

  1. <asp:GridView ID="gridTest" runat="server" OnRowDataBound="gridTest_RowDataBound" AutoGenerateColumns="false">  
  2.   
  3. <Columns>  
  4.   
  5.      <asp:BoundField HeaderText="Status" DataField="Status" />  
  6.   
  7.      <asp:BoundField HeaderText="Name" DataField="Name" />  
  8.   
  9.      <asp:BoundField HeaderText="Comment" DataField="Comment" />  
  10.   
  11.      <asp:BoundField HeaderText="Date" DataField="Date" />  
  12.   
  13. </Columns>  
  14.   
  15. </asp:GridView>  
Now we have the asp.net gridview, why not choose the highlighted row's color? Let's define a style sheet class for highlighted row.

  1.   
(The gridview markup shown above is only for example purpose. So you will not see any matches between the figure showing highlighted row and the example markup. Further you will also need to implement your own css styling, if you prefer any). Note the OnRowDataBound event handler in the gridview design markup. We will write some lines of code in this event handler to add the effect of highlighting gridview rows on mouse over. Here goes the code.

  1. //row created event  
  2.     protected void gridTest_RowCreated(object sender, GridViewRowEventArgs e)  
  3.     {  
  4.         if (e.Row.RowType == DataControlRowType.DataRow)  
  5.         {  
  6.             e.Row.Attributes.Add("onmouseover""this.className='highlightrow'");  
  7.             e.Row.Attributes.Add("onmouseout""this.className='normalrow'");  
  8.         }   
  9.     }  
We have specified the css class to adapt by the gridview row on mouse over. At the same time, we need to assign another css class on mouse out so that the gridview will be highlighted only on mouseover and on mouse out the effect will be void. Happy programming!