Click here to Skip to main content
Email Password   helpLost your password?

Introduction

This article describes another DataGrid control. Datagrids are very flexible, this one just inherits from the class DataGrid and adds the mouse over event to change the color of the row as the Code Project tables. Got the idea from Chris Maunder tables on Code Project. I looked at his JavaScript and I implemented into the .NET DataGrid class.

Using the code

This is a customer control. I include the source code for the control and a test project how to use it. As any customer control, you need to add the reference to the project. On the ASPX page:

(...)
< MOD:MODataGrid> id="DataGrid1" style="Z-INDEX: 101; 
  LEFT: 320px; POSITION: absolute; TOP: 136px"
  runat="server">

On the aspx.cs file add:

  protected MouseOverDataGrid.MODataGrid DataGrid1;  

I used the Datagrid tutorial example from http://asp.net for the test project

The Control

A simple Inherit from Datagrid class and overriding the Render function with Chris Maunder JavaScript. There are 2 public properties, the SpecialLinkColor as default set to CodeProject mouseover color that you can set to any color you like. And OverLinkHand to display the cursor as a Hand. I did not implement the method for on-click but it is on the JavaScript, so you can always implement it.

 [assembly:TagPrefix("MouseOverDataGrid", "MOD")]
namespace MouseOverDataGrid
{
 /// <summary>

 /// Summary description for MouseOverDataGrid.

 /// </summary>

 public class MODataGrid : System.Web.UI.WebControls.DataGrid
 {  

  [Category("Design"), Description("OverLink Color")]
  private string sBackgroundColor = "#dddddd";
  public string SpecialLinkColor
  {
   get{return(sBackgroundColor);}
   set{sBackgroundColor=value;}
  }

  [Category("Design"), Description("OverLink Hand Type")]
  private bool bOverLinkHand = false;
  public bool OverLinkHand
  {
   get{return(bOverLinkHand);}
   set{bOverLinkHand=value;}
  }

  protected override void Render(System.Web.UI.HtmlTextWriter writer)
  {
   string sDataGridID = this.ID.ToString();

   string sCursor = "";
   if ( OverLinkHand == true )
    sCursor = "elm.style.cursor = Cursor;\r";

   string sJavaScript = "< script language="'\""javascript\"'>\r" +
    "function ShowRow1(elm, BgColour, FgColour)\r" +
    "{\r" +
    "elm.bgColor = BgColour;\r" + sCursor +
    "}\r" +
    "function HilightRow(elm, hover, highlight)\r" +
    "{\r" +
    " var BgColour = (hover)? \"" + SpecialLinkColor + "\" :  \"white\";\r" +
    " var FgColour = \"black\";\r" +
    " var Cursor   = (hover)? \"hand\" :  \"auto\";\r" +
    " ShowRow1(elm, BgColour, FgColour);\r" +
    " return false;\r" +
    "}\r" +
    "function RowOn()  { return HilightRow(this, true, false);  }\r" +
    "function RowOff() { return HilightRow(this, false, false); }\r" +
    "function RowClick()\r" +
    "{\r" +
    " HilightRow(this, false, true);\r" +
    " var elm = eval('document.getElementById(\"' + this.name + '_link\")');\r" +
    " if (elm) elm.click();\r" +
    " return true;\r" +
    "}\r" +
    "var table = document.getElementById(\"" + sDataGridID + "\");\r" +
    "var rows = table.getElementsByTagName(\"tr\");\r" +
    "for (var i = 0; i < rows.length; i++) {\r" +
    "rows[i].onmouseover = RowOn;\r" +
    "rows[i].onmouseout  = RowOff;\r" +
    //"rows[i].onclick     = RowClick;" +

    "}\r</script>\r";
  


   base.Render (writer);   
   base.Page.Response.Write(sJavaScript);
  }

 }
  

Points of Interest

For the Datagrid to work you have to make sure you do not add any color on the item background. If you are using paging, add same color in the footer.

You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
GeneralHow to implement paging in your Datagrid custom control
karunakarrao
2:09 23 Feb '05  
Here i wrote this event in custom class

protected override void OnPageIndexChanged(DataGridPageChangedEventArgs e)
{
base.CurrentPageIndex = e.NewPageIndex;
base.PageSize = 5;

}

GeneralAnother Implementation
6:50 19 Jul '04  
Inherit from the DataGrid and override the OnItemDataBound virtual method.
Also, I put two properties in the data grid, MouseOverCssClass and MouseOutCssClass, that will allow you to set the respective css classes as design time.

public class ActiveDataGrid : System.Web.UI.WebControls.DataGrid
     {
          /// <summary>
          /// Css Class for the mouse over data grid row client-side event.
          /// </summary>
          [CategoryAttribute("Appearance")]
          public string MouseOverCssClass
          {
               get
               {
                    object cssClass = this.ViewState["MouseOverCssClass"];
                    if (cssClass != null)
                    {
                         return ((string) cssClass);
                    }
                    return string.Empty;
               }
               set { ViewState["MouseOverCssClass"] = value; }
          }

          /// <summary>
          /// Css Class for the mouse out data grid row client-side event.
          /// </summary>
          [CategoryAttribute("Appearance")]
          public string MouseOutCssClass
          {
               get
               {
                    object cssClass = this.ViewState["MouseOutCssClass"];
                    if (cssClass != null)
                    {
                         return ((string) cssClass);
                    }
                    return string.Empty;
               }
               set { ViewState["MouseOutCssClass"] = value; }
          }
         
          protected override void OnItemDataBound(DataGridItemEventArgs e)
          {
               if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
               {
                    e.Item.Attributes.Add("onmouseover", "this.className = '" + MouseOverCssClass + "';");
                    e.Item.Attributes.Add("onmouseout", "this.className = '" + MouseOutCssClass + "';");
               }
               base.OnItemDataBound(e);
          }
     }

< The Code Provider />
GeneralRe: Another Implementation
7:15 19 Jul '04  
Sorry for the extra thread.

CodeProject's servers was really slow and I posted it twice by accident.

Smile

< The Code Provider />
GeneralAnother Implementation
The Code Provider
6:18 19 Jul '04  
Inherit from the DataGrid and override the OnItemDataBound virtual method.
Also, I put two properties in the data grid, MouseOverCssClass and MouseOutCssClass, that will allow you to set the respective css classes as design time.

public class ActiveDataGrid : System.Web.UI.WebControls.DataGrid
     {
          /// <summary>
          /// Css Class for the mouse over data grid row client-side event.
          /// </summary>
          [CategoryAttribute("Appearance")]
          public string MouseOverCssClass
          {
               get
               {
                    object cssClass = this.ViewState["MouseOverCssClass"];
                    if (cssClass != null)
                    {
                         return ((string) cssClass);
                    }
                    return string.Empty;
               }
               set { ViewState["MouseOverCssClass"] = value; }
          }

          /// <summary>
          /// Css Class for the mouse out data grid row client-side event.
          /// </summary>
          [CategoryAttribute("Appearance")]
          public string MouseOutCssClass
          {
               get
               {
                    object cssClass = this.ViewState["MouseOutCssClass"];
                    if (cssClass != null)
                    {
                         return ((string) cssClass);
                    }
                    return string.Empty;
               }
               set { ViewState["MouseOutCssClass"] = value; }
          }
         
          protected override void OnItemDataBound(DataGridItemEventArgs e)
          {
               if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
               {
                    e.Item.Attributes.Add("onmouseover", "this.className = '" + MouseOverCssClass + "';");
                    e.Item.Attributes.Add("onmouseout", "this.className = '" + MouseOutCssClass + "';");
               }
               base.OnItemDataBound(e);
          }
     }

Smile

<The Code Provider />
GeneralSeems awful complicated for such a simple task
ShamusFu
8:34 16 Jul '04  
Why not just use the data bound event handler and do it there?

Most data grids vary enough from each other within an app that you are writing code in the data bound event handler anyway.

Interesting encapsulation, but it seems to take a really simple concept and make it complicated. Maybe if it were part of a much more elaborate custom data grid it would be worth doing.
GeneralAnother Approach
Brian Nash
6:18 16 Jul '04  
's in internet explorer
e.Item.Attributes.Add("OnMouseOver", "this.className = 'gridRow_MouseOver';");
e.Item.Attributes.Add("OnMouseOut", "this.className = 'gridRow_MouseOut';");
break;
default:
break;
}
}
I switched out the stylesheet class used when hovering over a row, that way it's easy to change the colors later. But you could just change the style to whatever you want.

Thanks for the article, casting light on something that's not totally obvious.Smile
Don't get me wrong, your approach is fantastic, but here's another way to skin this cat:

Add a handler for the "ItemDataBound" event
private void InitializeComponent()
{
this.dgGrid.ItemDataBound += new System.Web.UI.WebControls.DataGridItemEventHandler(this.UserDataBind);
this.Load += new System.EventHandler(this.Page_Load);
}

// in the handler set up the attributes for the client side OnMouseOver and OnMouseOut Events
private void UserDataBind(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
{
switch ( e.Item.ItemType )
{
case ListItemType.SelectedItem:
case ListItemType.Item:
case ListItemType.AlternatingItem:
// these two lines add client-side mouseover & mouseout handling
// Basically, this changes the style when the mouse is moved over and off of a row
// Seems like it would be better if the whole row had a style attached and the style
// handled this, but alas, hover (the 'event' that occurs when you mouseover something)
// isn't supported by
GeneralRe: Another Approach
Brian Nash
6:21 16 Jul '04  
On a second, more detailed, reading of the original article I see that the author encapsulated everything within a control and my "solution" didn't. You would have to put the itemboundevent handler into every page using a grid with my idea.
GeneralRe: Another Approach
ttestingonly
9:15 16 Jul '04  
Thanks Brain Nash to share one of generic way of implementations of this kind of topic.Smile
Generalif used two controls,how to?
linhaiyuan
20:29 27 Jun '04  
if used two controls,how to?
GeneralHandle right click
enjoycrack
17:00 16 Jun '04  
Please help me : How to handle right click on each row in data grid?
Thanx

Cry Sleepy
GeneralEnter key to work like tab key
rags
4:34 2 Jun '04  
Any idea how to make enter key work like tab key inside the datagrid?
ThanksConfused
GeneralRe: Enter key to work like tab key
jbrink5000
16:26 28 Jun '06  
public override bool PreProcessMessage(ref System.Windows.Forms.Message msg)

{

// the following code will make the 'Enter' key function as if it were the '' key.



// if a message is sent to this object of an 'Enter' (carriage return) control key,

if (((msg.LParam == new IntPtr(1835009)) || (msg.LParam == new IntPtr(18612225))) && (msg.WParam == new IntPtr(13)))

{

// then, we want to trick or fake out the OS to believe the user had stiked the 'TAB' key.



IntPtr l = new IntPtr(983041);

msg.LParam = l;



IntPtr w = new IntPtr(9);

msg.WParam = w;

}



return base.PreProcessMessage (ref msg); // call the base proc

}



GeneralWhy separate control
Bee Master
20:47 24 May '04  
You can have similar mouseover effect by including following code in ItemDataBound event handler of the DataGrid. There is no need for separate control.

if(e.Item.ItemType==ListItemType.Item || e.Item.ItemType==ListItemType.AlternatingItem)
{
e.Item.Attributes.Add("onmouseover", "this.style.backgroundColor='Silver'; this.style.cursor='hand';");
e.Item.Attributes.Add("onmouseout", "this.style.backgroundColor='white'; this.style.cursor='hand';");
}


//Start of joke
Never comment ur code. If it was hard to write, it should be hard to understand !!!
//End of joke

GeneralRe: Why separate control
zaf
0:03 25 May '04  
Nice and consise.

Any ideas how the row can revert to either the background color (which may have been set to alternate) or to the selected row color if the mouse pointer leaves the selected row?


GeneralRe: Why separate control
pmpjr
7:36 3 Jun '04  
If you are going to use this method, then just grab the backgroundColor before changing it and put it into a temp string so you can reuse it as follows:


if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
string strTempColor = (e.Item.ItemType == ListItemType.Item) ? ColorTranslator.ToHtml(DataGrid1.ItemStyle.BackColor) : ColorTranslator.ToHtml(DataGrid1.AlternatingItemStyle.BackColor) ;
e.Item.Attributes.Add("onmouseover", "this.style.backgroundColor='powderblue'; this.style.cursor='hand';");
e.Item.Attributes.Add("onmouseout", "this.style.backgroundColor='" + strTempColor + "';");
}


There is no place like 127.0.0.1!
GeneralRe: Why separate control
Albert Pascual
6:19 25 May '04  
In my web applications I have almost a DG in every page. I am a believer than instead of writing every single time the configuration of that DG is just better to Inherit the class Datagrid and then make all the modifications. I added so much to MyDataGrid class by now that was even hard to take everything off, but the Mouse Over event, to post the article here.

Al
GeneralRe: Why separate control
spvarapu
1:51 25 May '05  
Thank you very much ...i am giving 5 marks to youRose

Sreenivasulu Palavarapu
Lera Technologies,
Secunderabad.


Last Updated 25 May 2004 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2010