user279521
user279521

Reputation: 4807

Do a database query on Textbox onblur event

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 ?

Upvotes: 6

Views: 10676

Answers (3)

Aaronaught
Aaronaught

Reputation: 122634

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.

Upvotes: 5

Dustin Laine
Dustin Laine

Reputation: 38503

This should do the trick, as referenced here: http://www.codedigest.com/CodeDigest/80-Calling-a-Serverside-Method-from-JavaScript-in-ASP-Net-AJAX---PageMethods.aspx

These are the controls

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="True" />
<asp:TextBox ID="txtTest" onblur="LookupProduct()" runat="server" />

This is the Javascript

<script language="javascript">
function LookupProduct()
{  
    PageMethods.LookupProduct('',OnSuccess, OnFailure);
}

function OnSuccess(result) {
    if (result)
    {
    }
}

function OnFailure(error) {
}
</script>

This is the server sidewebmethod

[WebMethod]
public static bool LookupProduct()
{
    return true;
}

Upvotes: 1

jrummell
jrummell

Reputation: 43077

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
}

Upvotes: 3

Related Questions