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

廉价感情. 提交于 2020-01-15 10:09:53

问题


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)


回答1:


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,",");



回答2:


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);



回答3:


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);
    }
}


来源:https://stackoverflow.com/questions/45278117/how-to-get-multiple-selected-items-in-asp-net-listbox-and-show-in-a-textbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!