没有很好地使用asp列表框

本文关键字:asp 列表 很好 | 更新日期: 2023-09-27 18:24:50

我只想点击一个按钮,文本框中的文本就会自动添加为列表框中的一个项目。这不是应该直截了当吗?调试时,添加了该项,我可以通过观看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>

没有很好地使用asp列表框

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

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

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

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