Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do a database query on Textbox onblur event

Tags:

c#

asp.net-3.5

I am using asp.net 3.5 with C#. I need to do a database lookup when a user enters ProductID in txtProductID. I guess doing javascript is out of the question since this will have to be server side call. I wrote this code in the page_load event of the webpage:

        protected void Page_Load(object sender, EventArgs e)
    {
        txtProductID.Attributes.Add("onblur", "LookupProduct()");
    }

        protected void LookupProduct()
    {
        //Lookup Product information on onBlur event;
    }

I get an error message: Microsoft JScript runtime error: Object expected How can I resolve this ?

like image 816
user279521 Avatar asked Mar 11 '10 18:03

user279521


2 Answers

onblur is a client-side event. LookupProduct is a server-side method. You can't reference one from the other - there's simply no association whatsoever between the two.

There's no quick fix for this - you have to either trigger a postback on the client event (using ClientScriptManager.GetPostBackEventReference) or implement an Ajax callback using a library like Microsoft ASP.NET Ajax.

Alternatively, if you don't really need to fire this event on every blur, and only when the text has changed, then you can simply use the server-side TextBox.OnChanged event and set the TextBox's AutoPostBack property to true. Make sure you remember to set AutoPostBack, otherwise this won't get you anywhere.

like image 107
Aaronaught Avatar answered Sep 21 '22 17:09

Aaronaught


Use the TextBox.TextChanged event.

ASPX markup:

<asp:TextBox ID="txtProductID" runat="server" AutoPostBack="true" OnTextChanged="txtProductID_TextChanged" />

Codebehind:

protected void txtProductID_TextChanged(object sender, EventArgs e)
{
   // do your database query here
}
like image 45
jrummell Avatar answered Sep 17 '22 17:09

jrummell