Cause a PostBack on KeyPress from the asp.net dropdownlist

I recently bumped into a solution given by Vince Xu where he suggested a technique of causing a postback from a dropdownlist on any keypress. If you desire, you can easily filter the key code and cause postback on specific keypress. This technique can be useful when you plan to Implementing KeyBoard Shortcuts in ASP.NET applications 

Here’s how to cause a postback from DropDownList on keypress

C#

protected void Page_Load(object sender, EventArgs e)
{
if (Request.Params["__EVENTTARGET"] != null)
{
string evnt = Request.Params["__EVENTTARGET"].ToString();
string args = Request.Params["__EVENTARGUMENT"].ToString();
if (evnt == "DropDownList1" && args == "onkeypress")
{
// write some code to execute on postback
}
}

DropDownList1.Attributes.Add("onkeypress",
Page.GetPostBackEventReference(DropDownList1,"onkeypress"));
}



VB.NET




Protected Sub Page_Load(ByVal sender As Object, _
ByVal e As EventArgs)
If Request.Params("__EVENTTARGET") IsNot Nothing Then
Dim
evnt As String = _
Request.Params("__EVENTTARGET").ToString()
Dim args As String = _
Request.Params("__EVENTARGUMENT").ToString()
If evnt = "DropDownList1" _
AndAlso args = "onkeypress" Then
' write some code to execute on postback
End If
End If

DropDownList1.Attributes.Add("onkeypress",_
Page.GetPostBackEventReference(DropDownList1, "onkeypress"))
End Sub






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

No comments: