This is something which has always puzzled me.
If I want to make a custom control, in this case a child of the Datagrid control, but I want to ensure that when I hover my mouse over a specific cell, there is a rollover colour. If the datagrid doesn’t have any provision of doing this (For argument’s sake), do I have to get the co-ordinates of the mouse in relation to the cell and then highlight the closest cell?
Thanks
Rollover color should be defined using style sheets, or JavaScript. This would not be directly controlled through ASP.NET. You should have your server control generate either CSS classes to be used for defining hover styles, or generate inline JavaScript.
Using CSS is the best option, however it won’t work in IE6 (and maybe IE7, I can’t remember). This example assumes your control generates the data grid as an HTML table. Since your question says “custom server controls”, this may be different if you’re rendering your control with different markup. Make sure your table has a CSS class of
MyDataGridClass.If you want to highlight an entire row, you would change the
tdtotrin the example above.If you want a hover style in IE6 and you only need to highlight a single cell, you can do better by using an
<a />tag inside each cell. IE6 implements the hover pseudo-selector incorrectly so it only works on<a />tags, which is why this will work, but the above won’t in IE6:This example assumes, of course, that you have the ability to embed CSS into the page your control will be placed on. If for some reason you don’t have this option, you can go the JavaScript route, but this is not the preferred way to do things. If you’re interested in seeing how you’d go about this using JavaScript, just let me know.
UPDATE:
The section below addresses the first comment you left. I’ve kept the original in case someone finds it useful.
In order to create an event driven control, you should implement the
IPostBackEventHandlerorIPostBackDataHandler. If you need to understand the difference between these 2 interfaces, you can see this question. I’d rather not include the details here because it would make this answer too long.This example uses the
IPostBackEventHandler, but theIPostBackDataHandleris pretty similar.You need to do a few things to handle PostBack events:
base.Eventkey/value collection. In this example, I’m using the_EventClickobject.base.Events[]so that event subscribers are maintained across postbacks.Page.ClientScript.GetPostBackEventReference. This will generate a function call to ASP.NET’s__doPostBackJavaScript method. You can use this script in any JavaScript event attributes you render.This is a very minimal re-creation of the ASP.NET LinkButton control. Most of the “magic” happens in the
AddAttributesToRender()and theRaisePostBackEvent()methods.If you want to include additional JavaScript logic with your control, I suggest you read this article on including JavaScript with ASP.NET to see how to register scripts with ASP.NET.