简体   繁体   中英

How to update text in a textbox by changing item of a dropdownlist in the same listview row

I have an asp.net paget with an ListView. I want automatically change the text of an textbox when a certain value in a dropdownlist of the same listview- row is selected. How to I fire the event and change the textbox.text of the same row as the dropdownlist?

You can do this by casting the NamingContainer of the sender back to a ListView DataItem and use FindConrol to locate the TextBox.

<asp:ListView ID="ListView1" runat="server">
    <ItemTemplate>

        <asp:DropDownList ID="DropDownList1" runat="server" 
           OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" AutoPostBack="true">
            <asp:ListItem>Item A</asp:ListItem>
            <asp:ListItem>Item B</asp:ListItem>
            <asp:ListItem>Item C</asp:ListItem>
        </asp:DropDownList>

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

    </ItemTemplate>
</asp:ListView>

Code behind.

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
    //cast the sender back to a dropdownlist
    DropDownList ddl = sender as DropDownList;

    //get the current listview dataitem from the dropdownlist namingcontainer
    ListViewDataItem item = ddl.NamingContainer as ListViewDataItem;

    //find the textbox in the item with findcontrol
    TextBox tb = item.FindControl("TextBox1") as TextBox;

    //set the text
    tb.Text = ddl.SelectedValue;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM