Monday, March 1, 2010

When you build a web control inheriting from WebControl you will see AccessKey as a property and assume that if you assign to it that it will appear in the HTML produce. WRONG.

Not only does it not appear but if you naively do something like

this.Attributes.Add(“accesskey”,AccessKey);

you will see it in the HTML but usually it will NOT work….

The first problem is that the accesskey is valid only on a few html elements according to W3C. They are:

A

Area

Button

Input

Label

Legend

TextArea

Tables elements, divisions and spans may NOT use accesskey So what happens when you want to have the access key jump to a pure data <table>. The answer is simple, add a

<a name=”xyz” accesskey=”V” />

None of the other items are appropriate. This also answers the question when you wish to give an access key to a <span>, <div>, <ul>. <ol>, etc etc etc.

So if you are writing a webcontrol based on web control then you want to do something like this:

// If an access key was assigned to this control add an A element at the topif (!String.IsNullOrEmpty(AccessKey))
{
HtmlGenericControl accessA =new HtmlGenericControl("a");
// make sure it is unique accessA.Attributes.Add("name", string.Format("A_{0}", ClientID));
accessA.Attributes.Add("accesskey", AccessKey);
Controls.Add(accessA);
}

Now you have a functional Access Key pointing to your Web Control that conforms to HTML standards.