asp.netvb.netcustom-controlspostbackcomposite-controls

Postback From Controls inside Composite Web Control


Let's say we have a composite web control with a combobox and a textbox. Is it possible to build into the control functionality such that when the text in the textbox changes, it posts back and adds the value as an option in the combobox?

I know that I could add an "onchange" handler to the textbox and make something work with Javascript, but that's not really what I'm looking to do. Is there a way to just put like:

Protected Sub txt1_TextChanged(sender As Object, e As System.EventArgs) Handles txt1.TextChanged
    combo1.items.add(txt1.Text)
End Sub

in the web control code and it connect to the TextChanged event of the textbox?


Solution

  • In short yes, you should be able to do this.

    I don't know what syntax you need for VB, but I have done similar things multiple times in C#. For C# you would add the name of the even handler to the markup of your text box, and set auto postback on the text box to true. Then the code behind event handler does what ever work you need it to.

    As a rule I also define a custom event on the web control, and have the event handler for the textbox raise this custome event as well. This gives the option of letting the page that is using the control act on the event as well.

    EDIT:

    Here is an example with a DropDownList, it was part of a control to look up users within a set of Active Directory domains. If the user changed what domain they had selected we wanted it to search for the previously entered values on the new domain.

    Mark-up:

    <asp:DropDownList ID="ddl_Domain" runat="server" onselectedindexchanged="ddl_Domain_SelectedIndexChanged" AutoPostBack="True"></asp:DropDownList>
    

    Code behind:

    protected void ddl_Domain_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (UserID != "" || LastName != "" || FirstName != "" || EmailAddress != "")
        {
            lnk_Find_Click(sender, e);
        }
    }
    

    Or in the case where I have added a child control dynamically through code I have used this syntax:

    DropDownList ddl = new DropDownList();
    ddl.ID = "ddl";
    ddl.DataTextField = "Text";
    ddl.DataValueField = "Value";
    ddl.SelectedIndexChanged += This_SelectedValue_Changed;
    ddl.AutoPostBack = true; 
    

    As I said, I am not sure how to make this work with the Handles syntax of VB but it should be possible.