Get multiple selected items in ListBox

Madhuk
Posted by Madhuk under C# category on | Points: 40 | Views : 4060
<asp:ListBox ID="ListBox1" SelectionMode="Multiple"  runat="server">
<asp:ListItem>one</asp:ListItem>
<asp:ListItem>two</asp:ListItem>
<asp:ListItem>three</asp:ListItem>
</asp:ListBox>


private void GetSelectedItems()
{
// where str array are the selected list items
string[] str = { "one", "three" };
foreach (string item in str)
{
for (int x = 0; x <= ListBox1.Items.Count - 1; x++)
{
if (ListBox1.Items[x].Text == item)
{ ListBox1.Items[x].Selected = true; }
}
}
}

Comments or Responses

Posted by: T.saravanan on: 12/16/2010 Level:Silver | Status: [Member] [MVP] | Points: 10
Hi Madhuk,

Nice Try... But small mistake in your code...Just change it in your code..

 

for (int i = 0; i <= ListBox1.Items.Count - 1; i++)
{
if (ListBox1.Items[i].Text == item)
{
ListBox1.Items[i].Selected = true;
}
}


Cheers :)

Posted by: T.saravanan on: 12/16/2010 Level:Silver | Status: [Member] [MVP] | Points: 10
Hi Madhuk,

Sorry for my mistake actually in our dotnetfunda brace of 'i' can refer italic type then only it cannot show.
Just change the integer variable in your forloop..

for (int x = 0; x <= ListBox1.Items.Count - 1; x++)
{
if (ListBox1.Items[x].Text == item)
{
ListBox1.Items[x].Selected = true;
}
}


Posted by: Madhuk on: 12/16/2010 Level:Starter | Status: [Member] | Points: 10
Thanks for pointing it. I was just checking the code but could not find anything wrong. Now changed it.

Login to post response