Y2theZ
Y2theZ

Reputation: 10412

Changing A label text without PostBack (using Update Panels)

i created an ASP.NET Website. What i want to do is to make a label change its content depending on the item selected by a drop down list. I tried this but it didn't work:

The Drop down list looks like this:

<asp:DropDownList ID="DropDown1" runat="server" >
    <asp:ListItem Value="a"></asp:ListItem>
    <asp:ListItem Value="b"></asp:ListItem>
    onselectedindexchanged="DropDown1_SelectedIndexChanged"
</asp:DropDownList>

the label:

<asp:Label ID="Label1" Text="" runat="server"/>

I want to do it without having to use PostBack.

I tried to use ajax Update panel Like this:

<asp:UpdatePanel runat="server" id="UpdatePanel" updatemode="Conditional">        
    <Triggers>
        <asp:AsyncPostBackTrigger controlid="DropDown1"                                       EventName="SelectedIndexChanged" />
    </Triggers>
    <ContentTemplate>
        <asp:Label ID="Label1" Text="" runat="server"/>
    </ContentTemplate>
</asp:UpdatePanel>

And in the DropDown1_SelectedIndexChanged Event in the code behind:

protected void DropDown1_SelectedIndexChanged(object sender, EventArgs e)
{
    Label1.Text = DropDown1.SelectedValue;
}

But this is not working.

Can anyone Help me with it?

Thank you very much for any help

Upvotes: 7

Views: 23852

Answers (3)

Matias Korn
Matias Korn

Reputation: 33

http://encosia.com/why-aspnet-ajax-updatepanels-are-dangerous/

Read that article about, why NOT use updatepanels, there is alot of other much better solutions for doing the job.

Upvotes: 0

sikender
sikender

Reputation: 5921

Here is your solution..

replace your dropdown aspx control with below one..

  <asp:DropDownList ID="DropDown1" runat="server" onselectedindexchanged="DropDown1_SelectedIndexChanged" AutoPostBack="true">
                <asp:ListItem Value="a"></asp:ListItem>
                <asp:ListItem Value="b"></asp:ListItem>
           </asp:DropDownList>

<asp:UpdatePanel runat="server" id="UpdatePanel" updatemode="Conditional">
    <ContentTemplate>
        <asp:Label ID="Label1" Text="test" runat="server"/>
    </ContentTemplate>

    <Triggers>
        <asp:AsyncPostBackTrigger controlid="DropDown1" EventName="SelectedIndexChanged" />
    </Triggers>
</asp:UpdatePanel>

Upvotes: 9

Coding Flow
Coding Flow

Reputation: 21881

You need to enable autopostback and put the event handler definition in the right place:

<asp:DropDownList ID="DropDown1" runat="server" onselectedindexchanged="DropDown1_SelectedIndexChanged" AutoPostBack="true">
                                <asp:ListItem Value="a"></asp:ListItem>
                                <asp:ListItem Value="b"></asp:ListItem>
                            </asp:DropDownList>

Upvotes: 5

Related Questions