Asp.Net: keyboard sort items

As proof of concept I wanted to sort images in a Grid by keyboard. The sort logic needed to be implemented on the server. My solution for this problem is a combination of Javascript and C#.

First add following html to you .aspx. Notice that the body tag has runat=”server” and a ID.
[code language=’html’]
<body runat=”server” ID=”bodyTag”>

[/code]

Now add the following JavaScript to your page. This script will fetch all keyboard input and press the corresponding button.
[code language=’js’]

document.onkeydown = checkKeycode
function checkKeycode(e) {
var keycode;
if (window.event) keycode = window.event.keyCode;
else if (e) keycode = e.which;
switch (keycode) {
case 37:
var obj = document.getElementById(”);
obj.focus();
obj.click();
break;
case 38:
var obj = document.getElementById(”);
obj.focus();
obj.click();
break;
case 39:
var obj = document.getElementById(”);
obj.focus();
obj.click();
break;
case 40:
var obj = document.getElementById(”);
obj.focus();
obj.click();
break;
}

}

[/code]

At last we need to add the following C# code to the page.
[code language=’c#’]
protected void Page_Load(object sender, EventArgs e)
{
//Ad clientside onkeypress event to the body
bodyTag.Attributes.Add(“OnKeyPress”, “keyhandlers()”);
}

protected void DownButton_Command(object sender, CommandEventArgs e)
{
//Just for testing
clickedLabel.Text = (string)e.CommandArgument;
}
[/code]

Enjoy, Pieter

Leave a Reply

Your email address will not be published. Required fields are marked *