简体   繁体   中英

C# Get Separate ListBox Items as strings

I'm a little bit confused on something. I wrote a code that will count the number of items in a ListBox and then write them into each cell of an excel file. Like this:

int test = ItemsList.Items.Count;

for (int i = 1; i < test; i++)
{
    foreach (string itemText in ItemsList.Items)
    {
        worksheet.Cells[i, 0] = new Cell(itemText);
    }
}

for (int i = test + 1; i < 100; i++)
{
    worksheet.Cells[i, 0] = new Cell("");
}

This writes the code into excel properly however instead of displaying each item in the listbox separately it only displays the very last item in all of the cells. Any thoughts on how I can get each item from the list as a separate string for each cell?

You can use string.Join(string separator, IEnumerable values)

More details: http://www.dotnetperls.com/string-join http://msdn.microsoft.com/en-us/library/dd783876(v=vs.110).aspx

You don't need to use 2 loops. Do something like:

    for (int i = 1; i <= test; i++)
    {
        worksheet.Cells[i, 0] = new Cell(ItemsList.Items[i-1]);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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