0

Why "SelectedValue" selects only the first value in my multiple selection mode ?

<dt>Tags:</dt><dd>
<asp:ListBox ID="ListTag" runat="server" SelectionMode="Multiple"
    DataSourceID="SqlDataSourceTag" DataTextField="tag_name" 
    DataValueField="tag_id">
</asp:ListBox>
<asp:SqlDataSource ID="SqlDataSourceTag" runat="server" 
    ConnectionString="<%$ ConnectionStrings:db_cc %>">
</asp:SqlDataSource>
</dd>
ListTag.SelectedValue = "Tag1"; <-- only this is selects
ListTag.SelectedValue = "Tag2";
1
  • SelectedValue represents only single value that's why you get first selected value. If you want to get all the selected value you need to iterate thru the items of list and check Selected property of each item and get the Value of it if it's true. Commented Feb 26, 2018 at 10:38

1 Answer 1

2

in your asp page you have this.

<asp:ListBox ID="ListTag"  runat="server" AutoPostBack="True" SelectionMode="Multiple" Width="250px">
    <asp:ListItem Selected="False" Text="Tag-1" Value="1">Tag - 1</asp:ListItem>
    <asp:ListItem Selected="False" Text="Tag-2" Value="2">Tag - 2</asp:ListItem>
    <asp:ListItem Selected="False" Text="Tag-3" Value="3">Tag - 3</asp:ListItem>
    <asp:ListItem Selected="False" Text="Tag-4" Value="4">Tag - 4</asp:ListItem>
    <asp:ListItem Selected="False" Text="Tag-5" Value="5">Tag - 5</asp:ListItem>
    <asp:ListItem Selected="False" Text="Tag-6" Value="6">Tag - 6</asp:ListItem>
    <asp:ListItem Selected="False" Text="Tag-7" Value="7">Tag - 7</asp:ListItem>
    <asp:ListItem Selected="False" Text="Tag-8" Value="8">Tag - 8</asp:ListItem>
    <asp:ListItem Selected="False" Text="Tag-9" Value="9">Tag - 9</asp:ListItem>
    <asp:ListItem Selected="False" Text="Tag-10" Value="10">Tag - 10</asp:ListItem>
</asp:ListBox>

then in your cs(Code Behind) in the event that you want you have this.

  for (int i = 0; i < lsBox.Items.Count; i++)
        {
            var item = lsBox.Items[i];
            string[] selectecvalues = new string[] { "1", "3", "6", "9" };

            if (selectecvalues.Contains(item.Value)) // or item.Text  if you like
            {
                lsBox.Items[i].Selected = true;
            }
        }

that will result in Tags 1,3,6,9 selectd

Sign up to request clarification or add additional context in comments.

5 Comments

It does not work. I have to programmatically select several tags. There is no need to check is some options are selected.
I dont't have method,,SetSelected'' in ListTag
I have ListTag.Items.Count = 0 so I can't looping for this, but I have options tags with multiple choices
@Daniel you need to load the data before, called the looping
Thanks @ThaNet I I forgot to add ListTag.DataBind(); :)

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.