如何在Asp.Net中更改文本框中文本的内容

时间:2013-12-02 03:25:11

标签: c# asp.net

这是一个微不足道的问题,但我似乎无法在我的代码中找到错误。我有一个数据绑定DropDownList连接到SQLDataSource。对于这个DropDownList,我已经向SelectedIndexChanged添加了一个EventListener,这样当我更改DropDownList时,我想更改我拥有的TextBox的文本。这是我的代码:

<body>
    <form id="form1" runat="server" enableviewstate="True">
//snip

        <asp:DropDownList ID="DropDownList" runat="server" DataSourceID="SqlDataSource1" DataTextField="name" DataValueField="Id" style="z-index: 1; left: 219px; top: 199px; position: absolute" OnSelectedIndexChanged="DropDownList_SelectedIndexChanged">
        </asp:DropDownList>

        <asp:TextBox ID="TextBox1" runat="server" EnableTheming="True" style="z-index: 1; left: 218px; top: 241px; position: absolute; height: 180px; width: 240px; resize:none; right: 514px;"></asp:TextBox>
    </form>
</body>

protected void Page_Load(object sender, EventArgs e)
    {
        //Make the event listeners for our drop down lists
        DropDownList.SelectedIndexChanged += new EventHandler(this.DropDownList_SelectedIndexChanged);

        TextBox1.Text = "onwon";
    }

    protected void DropDownList_SelectedIndexChanged(object sender, EventArgs e)
    {
        TextBox1.Text = "oooooo"; //This never gets executed

    }

感谢您的时间。

解决方案 - 为下拉列表启用AutoPostback为true。非常有用的参考资料可以在这里找到:http://msdn.microsoft.com/en-us/library/ms178472.ASPX

1 个答案:

答案 0 :(得分:2)

您的下拉列表未回发,请将AutoPostBack="True"添加到您的下拉列表标记中,如下所示:

<asp:DropDownList ID="DropDownList" 
                  runat="server" 
                  DataSourceID="SqlDataSource1" 
                  DataTextField="name" 
                  DataValueField="Id" style="z-index: 1; left: 219px; top: 199px; position: absolute" 
                  OnSelectedIndexChanged="DropDownList_SelectedIndexChanged"
                  AutoPostBack="True">
</asp:DropDownList>