June 11, 2009

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



'Like' us on our FaceBook page if you find this blog useful. Thanks!


Did you like this post?
kick it on DotNetKicks.com Save on Delicious
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

0 Responses to "Cause a PostBack on KeyPress from the asp.net dropdownlist"
 

Copyright © 2009-2012 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions