Friday, 4 January 2013

Adding hover text to ASP.NET controls

A Class : HoverHelper , you can drop into your project and use to allow your controls to have "HoverText". E.g can be applied to Listboxes , Dropdownlists etc

This is handy in the instances where a Dropdownlist's text may be long and extend beyond the control ..HoverText will show the full un-truncated List Item Text.

Usage:


Simply call the Class.Method and pass in the control you wish to have hover text. This can be called just after the listbox/Dropdownlist is bound.

HoverHelper.BindTooltip(MyDropdownListControl);

Reusable HoverHelper Class to drop into your project :

/// <summary>

/// Allows you to pass in a listcontrol or drop down on Pre Render or Page load , to allow your control to have

/// </summary>

public class HoverHelper
{

/// <summary>

/// Binds the tooltip.

/// </summary>

/// <param name="p">The page we want to bind a tool tip to all it's controls</param>

public static void BindTooltip(System.Web.UI.Page p)
{

if (p == null || p.Form == null)
{

return;
}
BindTooltip(p.Form.Controls);
}

/// <summary>

/// Binds the tooltip.

/// </summary>

/// <param name="cc">The contol collection we want to bind a tool tip to</param>

public static void BindTooltip(ControlCollection cc)
{

if (cc == null)
{

return;
}

for (int i = 0; i < cc.Count; i++)
{

try
{

Control c = cc[i];

if (c.HasControls())
{
BindTooltip(c.Controls);
}

else
{

if (c.GetType().IsSubclassOf(typeof(ListControl)))
{

ListControl lc = (ListControl)c;
BindTooltip(lc);
}
}
}

catch
{
}
}
}

/// <summary>

/// Binds the tooltip.

/// </summary>

/// <param name="lc">The list control or combo control we want to add a tool tip , hover text to.</param>

public static void BindTooltip(ListControl lc)
{

for (int i = 0; i < lc.Items.Count; i++)
{
lc.Items[i].Attributes.Add(
"title", lc.Items[i].Text);
}
}

}

No comments:

Post a Comment