如何通过更改同一列表视图行中的下拉列表项来更新文本框中的文本

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

我有一个带有 ListView 的 asp.net 页面。 I want automatically change the text of an textbox when a certain value in a dropdownlist of the same listview- row is selected. 如何触发事件并更改与下拉列表相同行的 textbox.text?

您可以通过将 senderNamingContainer 转换回 ListView 数据项并使用 FindControl 定位文本框来完成此操作。

<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>

后面的代码。

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;
}