1

I have a List Box which i want to get selected from a comma separated string but my code is not working.

ASPX:

<asp:ListBox ID="ListBox1" runat="server" SelectionMode="Multiple">
    <asp:ListItem Value="1">aaa</asp:ListItem>
    <asp:ListItem Value="2">bbb</asp:ListItem>
    <asp:ListItem Value="3">ccc</asp:ListItem>
    <asp:ListItem Value="4">ddd</asp:ListItem>
    <asp:ListItem Value="5">eee</asp:ListItem>
    <asp:ListItem Value="6">fff</asp:ListItem>
</asp:ListBox>

ASPX.CS: (Code)

string listboxvalues = "2,1,5";
for (int i = 0; i < ListBox1.Items.Count; i++)
{
    foreach (string category in listboxvalues.ToString().Split(','))
    {
        if (category != ListBox1.Items[i].Value) continue;
            ListBox1.Items[i].Selected = true;
            break;
    }
}

Expected Result: (The expected result is what i am expecting but the code is not selecting anything)

<asp:ListBox ID="ListBox1" runat="server" SelectionMode="Multiple">
    <asp:ListItem Value="1" Selected="True">aaa</asp:ListItem>
    <asp:ListItem Value="2" Selected="True">bbb</asp:ListItem>
    <asp:ListItem Value="3">ccc</asp:ListItem>
    <asp:ListItem Value="4">ddd</asp:ListItem>
    <asp:ListItem Value="5" Selected="True">eee</asp:ListItem>
    <asp:ListItem Value="6">fff</asp:ListItem>
</asp:ListBox>
3
  • What do you mean by my code is not working? This code as it is seems to select 1 2 and 5 in the ListBox Commented Oct 4, 2017 at 21:43
  • The expected result is what i am expecting but the code is not selecting anything Commented Oct 4, 2017 at 21:47
  • 3
    Where did you place the code behind? in the Page_Load? I just tested it and it worked... Are you sure there's nothing else that deselects the items? Commented Oct 4, 2017 at 21:53

1 Answer 1

1

ASPX.CS: (Code)

string listboxvalues = "2,1,5";

//declare a list

List<string> items = new List<string>()

for (int i = 0; i < ListBox1.Items.Count; i++)
{
    foreach (string category in listboxvalues.ToString().Split(','))
    {
        if (category != ListBox1.Items[i].Value) continue;
            items.Add(category);
            break;
    }
}

//then in your ListBox1

listBox1.DataSource = items;
        listBox1.DisplayMember = "Item";
        listBox1.ValueMember = "Value";
Sign up to request clarification or add additional context in comments.

1 Comment

List<string> items not have Item or Value properties?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.