PDA

View Full Version : c# help



Josh
12-11-2012, 01:22 AM
Zachafer

[Only registered and activated users can see links]

I dont get why that doesnt work.

Its for a kad feeder. Never really worked in c# before. lsttemp is a list containing both the ids and item names. And lstignore is the items to ignore.

I believe the problem is when it deletes the last thing in the list.

InvalidArgument=Value of '8' is not valid for 'index'.

^Thats the error I get.

And this line is highlighted:

if (lsttemp.Items[i].ToString().Contains(removelistitem))

j03
12-11-2012, 01:10 PM
InvalidArgument=Value of '8' is not valid for 'index'.


There is no 9th item in your list

Josh
12-11-2012, 02:04 PM
InvalidArgument=Value of '8' is not valid for 'index'.


There is no 9th item in your list

Any clue how to fix it? I know the problem, but Im not too sure about how to fix it. Right now its running with 9 items in the list to begin with. But every time it does it 1 is removed (Right now its only unbuyables showing up for kads)

drew010
12-11-2012, 02:48 PM
The root of the problem is that your inner loop and outer loop should be reversed. Since you can possibly change the list items from the outer loop while you are still running the inner loop, removing the last item from the list will cause problems.

Here are two different solutions, the first one is simpler, the second reverses your loops so the code should work without error.

This first example takes advantage of ListBox.FindString which does an efficient search of the list and uses only a single for loop of the ignore list.



for (int b = lstignore.Items.Count - 1; b >= 0; --b) {
string removelistitem = lstignore.Items[b].ToString();
int index = lsttemp.FindString(removelistitem);

if (index >= 0) {
lsttemp.Items.RemoveAt(index);
}
}


The second example is similar to what you had but is fixed by swapping the two loops around so its safe to change the first list in the second loop.



for (int b = lstignore.Items.Count - 1; b >= 0; --b) {
string removelistitem = lstignore.Items[b].ToString();

for (int i = lsttemp.Items.Count - 1; i >= 0; --i) {
if (lsttemp.Items[i].ToString().Contains(removelistitem)) {
lsttemp.Items.RemoveAt(i);
}
}
}


Hope that helps.

Josh
12-11-2012, 03:22 PM
That works perfect. Thanks for the help. :)

Zachafer
12-11-2012, 09:12 PM
You should probably use a custom class (ie Item.cs) for storing Item Names with corresponding IDs.

Josh
12-11-2012, 09:55 PM
I like my way. :P

j03
12-11-2012, 10:18 PM
Lol Zachafer knows his shit