Bhanu Tharun
Bhanu Tharun

Reputation: 134

How to get multiple selected items in asp.net listbox and show in a textbox?

i am trying to add the selected items from the listbox to the textbox with the comma seperated between each other. but it is only reading the first element of the selected items every time.if i select three values holding ctrl its only passing the fist elemnt of selected items

if (ListBox1.SelectedItem != null)
        {

            //   int count = ListBox1.SelectedItems.Count;
            if (TextBox1.Text == "")
                TextBox1.Text += ListBox1.SelectedItem.ToString();
            else
                TextBox1.Text += "," + ListBox1.SelectedItem.ToString();
        }

if listbox contain :1,2,3,4 example output inside textbox: 1,1,1,1 expected output: 1,2,3,4 (for evry selection it shouldnt display the already selected value again)

Upvotes: 1

Views: 5018

Answers (3)

Ravikumar
Ravikumar

Reputation: 625

Try this

 var selected =  string.Join(",", yourListBox.Items.GetSelectedItems());

public static class Extensions
{
    public static IEnumerable<ListItem> GetSelectedItems(
           this ListItemCollection items)
    {
        return items.OfType<ListItem>().Where(item => item.Selected);
    }
}

Upvotes: 0

Ramankingdom
Ramankingdom

Reputation: 1486

var selectedItemText =   new List<string>();
    foreach (var li in ListBox1.Items)
    {
       if (li.Selected == true)
        {
         selectedItemText.Add(li.Text);
        }
    }

Then

var result =   string.Join(selectedItemText,",");

Upvotes: 3

Romano Zumb&#233;
Romano Zumb&#233;

Reputation: 8079

The ListBox has a SelectedItems property, that you can iterate over:

foreach (var item in ListBox1.SelectedItems)
{
    TextBox1.Text += "," + item.ToString();
}

At the end you need to remove the first "," as it will be in front of the first items string representation:

TextBox1.Text = TextBox1.Text.Substring(1, TextBox1.Text.Legth - 1);

Upvotes: 2

Related Questions