简体   繁体   English

如何在C#中的字符串变量中存储列表框值

[英]how to store listbox values in a string variable in c#

I want to store all listbox control values in a string with "," separated so that I can show it in the label. 我想将所有列表框控件值存储在字符串中,并用“,”分隔,以便可以在标签中显示它。 I'm using for loop but giving error 我正在使用for循环,但给出错误

 for (int i = 0; i < ListBox2.Items.Count; i++){

        if (ListBox2.Items[i].Selected == true || ListBox2.Items.Count > 0){
            string projectnames += ListBox2.Items[i].ToString();
        }
  }
string projectnames = "";
bool firstValue = true;

for (int i = 0; i < ListBox2.Items.Count; i++)
            {

                if (ListBox2.Items[i].Selected == true || ListBox2.Items.Count > 0)
                {
                   if(!firstValue)
                   {
                      projectnames += ", " + ListBox2.Items[i].ToString();
                   }
                   else
                   {
                      projectnames += ListBox2.Items[i].ToString();
                      firstValue = false;
                   }

                }

            }

Instead of the loop i'd use LINQ + String.Join : 而不是循环,我将使用LINQ + String.Join

var selected = ListBox2.Items.Cast<ListItem>()
    .Where(li => li.Selected)
    .Select(li => li.ToString());
string projectnames = String.Join(",", selected);

On that way it's much better to read and you don't need to care about trailing commas. 这样一来,阅读起来会更好,而且您不必担心尾随逗号。

This will generate a string of all selected items in the list. 这将生成列表中所有选定项目的字符串。

string projectnames = "";
for (int i = 0; i < ListBox2.Items.Count; i++)
{

    if (ListBox2.Items[i].Selected)
    {
       projectnames += ListBox2.Items[i].ToString() + ", ";
    }

 }

The most succinct method I can think of is: 我能想到的最简洁的方法是:

var label = string.Join(",", listBox2.Items.Cast<string>());

(This uses System.Linq) (这使用System.Linq)

Try this, will help you! 试试这个,对您有帮助!

protected void btnSave_Click(object sender, EventArgs e)
    {
        string selectedItem=string.Empty;
        if (ListBox1.Items.Count > 0)
        {
            for (int i = 0; i < ListBox1.Items.Count; i++)
            {
                if (ListBox1.Items[i].Selected)
                {
                    selectedItem += ListBox1.Items[i].Text.ToString() + ", ";
                    //insert command
                }
            }
        }
    }

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

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