2012-02-15 49 views
3

我只想簡單地點擊一個按鈕,文本框中的文本就會自動添加爲列表框中的一個項目。這不應該是直截了當的嗎?調試時,項目被添加,我可以通過觀看ListBox1.Items [0]來查看文本,但是網頁中沒有顯示任何內容。我在控制檯應用程序中遇到了同樣的問題,我沒有解決這個問題!有人可以指導我做什麼我錯了嗎?不使用asp列表框

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

其空的!,但這是我的aspx頁面。 :UpdatePanel> – test 2012-02-15 20:26:05

回答

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

謝謝你!像魅力一樣工作!現在至少我知道我寫的代碼是好的,我現在必須找到與我的控制檯應用程序相同的問題!再次感謝! – test 2012-02-15 20:32:42

4

你必須列表框移動到UpdatePanel的,否則也不會被更新。

原因是,ASP.NET正在將UpdatePanel的整個HTML發送回客戶端。由於ListBox不是UpdatePanel的一部分,它不會被更新。

+0

Thanks!像魅力一樣工作! – test 2012-02-15 20:32:58