I have a ListView control which is definitely populated. The problem is that it's being treated as empty. When specifying an index of an item which I know is there, I get an "ArgumentOutOfRangeException" error.
public static string folderToUpdate(string folderChanged)
{
Main m = new Main(); // This is the class which this method is in,
// as a side matter I don't even know why I have to create
// an instance of the class I'm ACTUALLY IN
// (but I get a compile time error if I don't).
string folder1 = m.lstFoldersToSync.Items[0].Text;
string folder2 = m.lstFoldersToSync.Items[1].Text;
string folderToUpdate;
// If the folder changed is folder1 then the folder to update must be folder2.
// If the folder changed is folder2 then the folder to update must be folder1.
if (folderChanged == folder1)
{
folderToUpdate = folder2;
}
else
{
folderToUpdate = folder1;
}
return folderToUpdate;
}
The error comes at line 8 where I declare and define "folder1".
Some Clarifications: I have searched extensively before posting. No other question is an exact duplicate. There are many similar questions but the solution always turned out to be either an empty list problem or an "Off-by-one error", neither of these are the problem I'm having. Once again I stress the Listview is populated (on form load).
So what can it be? Could the problem have something to do with Main m = new Main();
?
Any help would be very much appreciated. Thank You.
PS: I think all the code besides lines 3, 8, and 9 are pretty much irrelevant (I may be wrong).
EDIT: I have solved the problem by using a static field list containing the contents of the "lstFoldersToSync" control, and then accessing that (instead of trying to access the contents of the control directly).
New working code:
private static List<string> foldersToSync = new List<string>(); // This will be populated with the items in "lstFoldersToSync" control on "Main" form.
public static string folderToUpdate(string folderChanged)
{
// Main m = new Main();
string folder1 = foldersToSync[0];
string folder2 = foldersToSync[1];
string folderToUpdate;
// If the folder changed is folder1 then the folder to update must be folder2.
// If the folder changed is folder2 then the folder to update must be folder1.
if (folderChanged == folder1)
{
folderToUpdate = folder2;
}
else
{
folderToUpdate = folder1;
}
return folderToUpdate;
}
Thank you very much for all those helped me.