开发者

list box manipulations

I am using a asp.net listbox. I have two buttons one to add items to listbox and another to remove. I am using javascript function to remove items from the listbox. When I add to the listbox after removing. The removed items are also getting added.

<asp:ListBox ID="sLstbox" runat="server" Width="250px" Height="150px" TabIndex="10"></asp:ListBox>

<asp:LinkButton ID="sLbtnAdd" runat="server" ></asp:LinkButton>&nbsp; 
<a href="#" id="hAncRemove" runat="server" onclick="fncRemoveItems();">Remove</a>    

function fncRemoveItems()
{
    var i;
    var strIDs="";
    var items = document.getElementById("sLstbox");
    alert(items.options.length);
    for (i = items.options.le开发者_如何学编程ngth - 1; i >= 0; i--)
    {
        if (items.options[i].selected)
            items.remove(i);
    }
}

IN code

Protected Sub sLbtnAdd_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles sLbtnAdd.Click

    Dim li As New ListItem
    li.Value = "1"
    li.Text = "test"
    sLstbox.Items.Add(li)
End Sub


You should be using normal < select > boxes in this case. asp:listboxes are meant to be manipulated at server side and you need to hack around that to make it work the way you want.

With normal select-boxes (either runat server or not) it should be pretty straight forward.


If you want to make your life a lot easier and give you the 'AJAX' effect, just put it all in an UpdatePanel and do it server side. If you want to use an asp:ListBox, manipulating it via javascript is going to a pain.

Here is a working example with the aspx code and the codebehind implementation for your scenario:

<asp:UpdatePanel ID="yourUpdatePanel" runat="server">
    <ContentTemplate>
        <asp:ListBox ID="sLstbox" runat="server" Width="250px" Height="150px" TabIndex="10"></asp:ListBox> 
        <asp:LinkButton ID="sLbtnAdd" runat="server" OnClick="sLbtnAdd_Click" ></asp:LinkButton>&nbsp;  
        <asp:LinkButton ID="sLbtnRemove" runat="server"  OnClick="sLbtnRemove_Click"></asp:LinkButton>&nbsp;        
    </ContentTemplate>
</asp:UpdatePanel>    

In your codebehind:

Protected Sub sLbtnAdd_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles sLbtnAdd.Click            
    Dim li As New ListItem      
    li.Value = "1"      
    li.Text = "test"      
    sLstbox.Items.Add(li)      
End Sub 

Protected Sub sLbtnRemove_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles sLbtnAdd.Click            
    For i As Integer = sLstbox.Items.Count - 1 To 0 Step -1
        If sLstbox.Items(i).Selected Then
            sLstbox.Items.Remove(sLstbox.Items(i))
        End If
    Next
End Sub 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜