tags:

views:

482

answers:

5

I've got a usercontrol that has a <asp:TextBox> with autopostback set to true. When the user types text in and moves off the textbox, asp.net fires a postback event. However, it isn't handled specifically by the textbox, but is instead simply a postback - the page_load fires and then life goes on.

What I need is a way to know that this textbox fired the event. I then want to fire my own custom event so that my main page can subscribe to it and handle the event when the textbox changes.

At first I thought I could capture the sender - I was assuming that the sender would be the textbox, but it appears to be the page itself.

Anyone have any thoughts?

A: 

Is this i dynamically created usercontrol or textbox? If so you have to recreate that control in the page_load event and the event should be fired on the textbox as normal.

sindre j
A: 

The page load sender will always be ASP.default_aspx because the page is what is calling that event.

You can hook up to the even OnTextChanged where that sender would be the textbox that has changed or caused the post back.

Keep in mind the page load will always fire before any of the events on the controls.

David Basarab
A: 

This is potentially something that could be overlooked, but do you actually have an event coded for the textbox's TextChanged event? If you have it set to autopostback but never actually created an event for it, you're only going to get your page load and other related events.

TheTXI
+1  A: 

I think you're missing something, so I want to explain it step by step :

your textbox should be something like that :

<asp:TextBox runat="server" ID="TextBox1" AutoPostBack="true" 
OnTextChanged="TextBox1_TextChanged"></asp:TextBox>

and in your codebehind you shhould have an event like that :

protected void TextBox1_TextChanged(object sender, EventArgs e)
{
    string str = TextBox1.Text;
}

NOTE : if you want to attach your event in code-behind you can do this by :

TextBox1.TextChanged +=new EventHandler(TextBox1_TextChanged);

but if you talking about custom controls, you should implement IPostBackDataHandler interface to raise events.

Canavar
A: 

As alluded to in other answers you need to handle the 'OnTextChanged' event.

<asp:TextBox ID="TextBox1" runat="server" OnTextChanged="TextBox1_TextChanged"></asp:TextBox>

private void TextBox1_TextChanged(object sender, System.EventArgs e)
{
    TextBox txt = (TextBox)sender;
    string id = txt.ID;

    switch(id)
    {
        case "TextBox1":
            break;
    }
}
Phaedrus