没有好好使用asp列表框

时间:2012-02-15 20:19:48

标签: c# asp.net listbox scriptmanager

我只想点击一个按钮,文本框中的文字会自动添加为列表框中的项目。这不应该是直截了当的吗?在调试时,添加了项目,我可以通过观看ListBox1.Items [0]来查看文本,但网页中没有显示任何内容。我在控制台应用程序中遇到了同样的问题,我没有解决!有人可以指导我做错了什么吗?

protected void Button1_Click(object sender, EventArgs e)
    {
        ListBox1.Items.Add(new ListItem(TextBox1.Text));
    }

非常感谢

编辑:

在过去的项目中,我使用了DataSource属性,该属性非常有效。我从来没有设法使用添加项目!可能有某种刷新或更新?

网页代码:

<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>

<asp:ListBox ID="ListBox1" runat="server" Height="150px" Width="295px"></asp:ListBox>

<asp:UpdatePanel ID="updatePanel1" runat="server">
    <ContentTemplate>
        <asp:Button ID="Button1" runat="server" Text="Submit" OnClick="Button1_Click" />
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    </ContentTemplate>
</asp:UpdatePanel>

2 个答案:

答案 0 :(得分:4)

您必须将ListBox移动到UpdatePanel中,否则不会更新。

原因是,ASP.NET正在将UpdatePanel的整个HTML发送回客户端。由于ListBox不是UpdatePanel的一部分,因此无法更新。

答案 1 :(得分:4)

您的列表框看起来不在更新面板中。在更新面板中弹出它:

<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
    <asp:DropDownList ID="DropDownList1" runat="server">
    </asp:DropDownList>
<asp:Button ID="Button1" runat="server" Text="Button" onclick="AddItem" />
</ContentTemplate>
</asp:UpdatePanel>