try this:
int n = listBox1.SelectedItems.Count;
string[] array = new string[n];
for (int i = 0; i < n; i++)
{
array[i] = listBox1.SelectedValue.ToString();
}
jatin24
Junior Poster in Training
75 posts since Aug 2009
Reputation Points: 31
Solved Threads: 21
Try this:
// What I would do
List<string> Strlist = new List<string>();
foreach (string str in listBox1.SelectedItems)
{
Strlist.Add(str);
}
// Or try the corrected jatin24 style
int n = listBox1.SelectedItems.Count;
string[] array = new string[n];
for (int i = 0; i < n; i++)
{
array[i] = listBox1.SelectedItems[i].ToString();
}
ddanbe
Senior Poster
3,829 posts since Oct 2008
Reputation Points: 2,070
Solved Threads: 661
string[] ar = listBox1.SelectedItems.Cast<string>().ToArray<string>();
__avd
Posting Genius (adatapost)
8,648 posts since Oct 2008
Reputation Points: 2,136
Solved Threads: 1,241
string[] ar = listBox1.SelectedItems.Cast<string>().ToArray<string>();
That is handy! For unboxing casts I have always used the .ConvertAll() but this is much easier to call :)
What I have been doing:
double[] sArray2 = lst.ConvertAll<double>(new Converter<decimal, double>(Convert.ToDouble)).ToArray();
sknake
Industrious Poster
4,954 posts since Feb 2009
Reputation Points: 1,764
Solved Threads: 735
serkan sendur
Postaholic
2,062 posts since Jan 2008
Reputation Points: 854
Solved Threads: 127
In terms of long lists and performance, Danny's solution is the best and to make it better use 'for' loop instead of 'foreach'
My test on 10000 items
Danny (for not foreach) | 39060 ticks
Danny | 48825 ticks
adatapost | 761670 ticks
Ramy Mahrous
Postaholic
2,196 posts since Aug 2006
Reputation Points: 480
Solved Threads: 276