简体   繁体   English

如何在asp.net列表框中获取多个选定项并在文本框中显示?

[英]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 但是它每次都只会读取所选项目的第一个元素。如果我选​​择三个按住ctrl的值,则它只会通过所选项目的第一要素

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,2,3,4文本框内的示例输出:1,1,1,1预期输出:1,2,3,4(对于evry选择,它不应再次显示已选择的值)

The ListBox has a SelectedItems property, that you can iterate over: ListBox具有SelectedItems属性,您可以对其进行迭代:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM