Jesse Roper
Jesse Roper

Reputation: 1309

Changing selected index of asp:gridview with keydown

I'm trying to allow changing of rows of a gridview using the up and down arrow keys. I was trying to use jquery to catch the keyup event and change the selected index using a hidden input field to store the value, but I'm not sure this is the right approach. Can anyone provide some insight on the best method to implement this feature?

Thanks in advance

Upvotes: 0

Views: 1472

Answers (1)

James Johnson
James Johnson

Reputation: 46067

This isn't the complete solution, but it should get you going in the right direction.

On the RowDataBound event, add an onkeypress or onkeyup event to the row, like this:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    //pass in an argument that will help to determine index of new selection
    //for this example, I just chose the row index
    e.Row.Attributes["onkeypress"] = String.Format("validateKeyPress({0});", e.Row.RowIndex);
}

Create the JavaScript function to validate key press and do a postback

validateKeyPress = function(rowIndex){
   //keycode 37 isn't the up or down key, but you get the idea
   //also make sure that the logic here is browser compatible
   if (window.event.keyCode == 37){ 
       __doPostBack("<%=GridView1.UniqueID%>", rowIndex);
   }
}

In code behind, add override for RiasePostBackEvent method:

protected override void RaisePostBackEvent(IPostBackEventHandler source, string eventArgument)
{
    if (source == GridView1)
    {
         //add proper validation to avoid out of bounds exception
         //this code increments, but you need to add something to increment or decrement 
         GridView1.SelectedIndex = Int32.Parse(eventArgument) + 1;
    }
}

Upvotes: 1

Related Questions