Click here to Skip to main content
15,885,954 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a list box which I have made an array from ...

public string[] getlistboxarray()
{
    string[] arr = new string[listBox2.Items.Count];
    for (int i = 0; i < listBox2.Items.Count; i++)
    {
        arr[i] = listBox2.Items[i].ToString();
    }
    return arr;
}


I have a start button, which when I click it removes the first item in the array. How would I do this?

What I have tried:

arr = arr.ToList().RemoveAt(0).ToArray();
Posted
Updated 24-Apr-18 10:07am
Comments
Maciej Los 24-Apr-18 16:04pm    
Why do you load items from listbox into array and them you want to remove first item?
Paulo Zemek 24-Apr-18 17:05pm    
You can't really remove items from an array. What you can do is create another array with less items and copy only the items you care about.

Yet, as you used ToList().RemoveAt(0) in your try, why can't you simply have a list, instead of an array, so you can very easily add or remove items?

Please, read my comment to the question first.

If you want to delete item from listbox, use: ListBox.ObjectCollection.RemoveAt Method (Int32) (System.Windows.Forms)[^]
If you want to remove item from array, use: Array.removeAt Function[^]
 
Share this answer
 
If you want to manipulate just the array, one simple way is to copy the data in the into the array variable and then resize it.

For example
C#
Array.Copy(arr, 1, arr, 0, arr.Length - 1);
Array.Resize(ref arr, arr.Length - 1);

ADDED
-----
Or as Paolo Zemek suggested
string[] arr2 = new string[listBox2.Items.Count - 1];
Array.Copy(arr, 1, arr2, 0, arr.Length - 1);
 
Share this answer
 
v4
Comments
Paulo Zemek 24-Apr-18 17:06pm    
Actually the Resize method always creates a new array. So it would be better to simply create a new array with Length-1, and then copy directly to the new array.
Yet, using a List instead of an array is probably still the best option.
Wendelius 24-Apr-18 23:11pm    
Good point, added copying to a new array.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900