locked
Select items in a list box RRS feed

  • Question

  • User41291981 posted

    Hello,

    I'm looking to select items in a list box based on the contents of a string. Lets say I have "comp1, comp2, comp3, comp4" stored in StringBuilder "company".  I would like to loop through company and select all of the companies if they exist in a list box.

    Is this possible? I'm VERY new to programming in general so go easy on me :)

    Thanks,

    Jon

    Wednesday, June 22, 2016 5:13 PM

Answers

  • User177399542 posted

    Hi

          Based on your requirements I have created a sample for you please check:

    <asp:ListBox runat="server" ID="lstBxCompany" SelectionMode="Multiple" Width="500" Height="200">
            <asp:ListItem Text="comp1" Value="comp1" />
            <asp:ListItem Text="Demo1" Value="Demo1" />
            <asp:ListItem Text="comp2" Value="comp2" />
            <asp:ListItem Text="comp3" Value="comp3" />
            <asp:ListItem Text="Demo2" Value="Demo2" />
            <asp:ListItem Text="comp4" Value="comp4" />
            <asp:ListItem Text="Demo3" Value="Demo3" />
        </asp:ListBox>
        <asp:Button Text="Check Values" ID="btnCheckValues" OnClick="btnCheckValues_Click" runat="server" />

    Code Behind:

     protected void btnCheckValues_Click(object sender, EventArgs e)
        {
            StringBuilder company = new StringBuilder("comp1, comp2, comp3, comp4");
            //--- Here we will split string values and store in array.
            string[] comp = company.ToString().Split(',');
    
            //---- Loop through each item stored in array.
            foreach (var c in comp)
            {
                //--- Loop through each item stored in Listbox
                foreach (ListItem li in lstBxCompany.Items)
                {
                    if (li.Text == c.Trim())//--- Here Trim() method is used to remove unwanted blank space.
                    {
                        li.Selected = true;
                    }
                }
            }
    
        }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, June 23, 2016 5:16 AM