Reputation: 273
Having trouble adding integers to the item array of a list box. Cannot seem to convert the listbox to integer.
int[] ratingArray = new int[numberRatingsInt];
for (int i = 0; i < numberRatingsInt; i++)
{
ratingArray[i] = Convert.ToInt32(ratingListBox.Items[i]);
}
Upvotes: 2
Views: 13632
Reputation: 941
Please try this
var modarray = ratingListBox.Items.Cast<String>().ToArray();
int[] arr = modarray.Select(int.Parse).ToArray();
Upvotes: 1
Reputation: 9064
Add .ToString()
to ratingListBox.Items[i]
It should be:
int[] ratingArray = new int[numberRatingsInt];
for (int i = 0; i < ratingListBox.Items.Count; i++)
{
ratingArray[i] = Convert.ToInt32(ratingListBox.Items[i].ToString());
}
Just Tested:
.value
after ratingListBox.Items[i]
can also work.
It can also work like following:
int[] ratingArray = new int[numberRatingsInt];
for (int i = 0; i < ratingListBox.Items.Count; i++)
{
ratingArray[i] = Convert.ToInt32(ratingListBox.Items[i].Value);
}
(This was tested added in reference to @Chris answer.)
Edit:
put ratingListBox.Items.Count
in for loop condition.
Upvotes: 2
Reputation: 15138
Just to add to the other answers, you can also do a sexy lambda something like:
int[] ratingArray = ratingListBox.Items.OfType<ListItem>()
.Select(x => int.Parse(x.Value))
.ToArray();
This should get rid of all the loops counts, consts etc.
Upvotes: 2
Reputation: 2895
ListBoxes
contain ListItems
, not the value directly. Try this:
int[] ratingArray = new int[numberRatingsInt];
for (int i = 0; i < numberRatingsInt; i++)
{
ratingArray[i] = Convert.ToInt32(ratingListBox.Items[i].Value);
}
Upvotes: 2