I am new to C# and I have encountered an error stating that: InvalidArgument=Value of '2' is not valid for 'index'.
I want to set the items in checkedlistbox checked if there is a match in listbox.
Can anyone help me with this problem.
This the part of my code where the problems appear.
for (int i = 0; i < checklistbox.Items.Count; i++)
{
if (checklistbox.Items[i].ToString() == listbox.Items[i].ToString())
{
//Check only if they match!
checklistbox.SetItemChecked(i, true);
}
}
You just need to use nested for loop. Here is the code.
for (int i = 0; i < listbox.Items.Count; i++)
{
for (int j = 0; j < checkedlistbox.Items.Count; j++)
{
if (listbox.Items[i].ToString() == checkedlistbox.Items[j].ToString())
{
//Check only if they match!
checkedlistbox.SetItemChecked(i, true);
}
}
}
The reason you are getting this error is because you are looping through the count of checklistbox items. So, for example if there are 3 items in that array, and listbox only has 2 items, then on the third loop (when i = 2), you are trying to reference an item in the listbox array that does not exist.
Another way to do it would be like this:
foreach (var item in listbox.Items)
{
if (Array.Exists(checklistbox.Items, lbitem => lbitem.ToString() == item.ToString()))
{
//They match!
checklistbox[item].MarkAsChecked()
}
}
Update: answer updated to add MarkAsChecked() and loop through user inputted values held within checklist array.
Related
For homework assignment we have to program a Intersection merge of 2 ArrayLists. I have done it using the following code
public void Intersection()
{
foreach (object obj1 in Developed)
{
Apps xApp = (Apps)obj1;
foreach (object obj2 in DPloyed)
{
Apps yApp = (Apps)obj2;
if (xApp.CompareName(yApp) == 0)
{
Inter.Add(yApp);
}
}
}
}
I would like to implement it rather using the while loop but the following code seems to keep missing elements in the list. It puts the first elements in the new intersection list but once the length of developed is increased from 1 element to 5 elements or more it does not add the new elements.
public void Intersection()
{
int i = 0;
int j = 0;
while (i < Developed.Count && j < DPloyed.Count)
{
Apps curA = (Apps)Developed[i];
Apps curB = (Apps)DPloyed[j];
if (curA.CompareName(curB) == 0)
{
Inter.Add(curA);
i++;
j++;
}
else if (curA.CompareName(curB) < 0)
{
i++;
}
else
j++;
}
}
Any help as to why the while loop does not work would be appreciated.
Thanks
Do this
while (i < Developed.Count || j < DPloyed.Count)
because may be both list may be having different Count.
and you need to put extra checks inside loop for indexes so that you don't get Index out of Range Exception.
Problem was not in the actual code for the merges. Problem found in my compare methods.
I have the following code.
I am trying to insert values into a listbox, and then be able to resort the values by alphabetical order and re display them in the same listbox. For some reason code doesn't work (no errors - just when i push the button the listbox clears)
protected void sortButton_Click(object sender, ImageClickEventArgs e)
{
string[] movieArray = new string [cartListBox.Items.Count];
for (int i = 0; i < cartListBox.Items.Count; i++)
{
movieArray[i] = cartListBox.Items[i].ToString();
}
Array.Sort(movieArray);
cartListBox.Items.Clear();
for (int i = 0; i < cartListBox.Items.Count; i++)
{
cartListBox.Items.Add(movieArray[i].ToString());
}
}
I think problem is in last loop.
Do that like follows:
cartListBox.Items.Clear();
for (int i = 0; i < movieArray.Length; i++)
{
cartListBox.Items.Add(movieArray[i].ToString());
}
When you are clearing cartListBox.Items.Clear();, it should not be taken for loop counter like, for (int i = 0; i < cartListBox.Items.Count; i++)
cartListBox.Items.Count was creating problem.
You can avoid all that looping, and your bug, by doing this in a more modern way:
var items = cartListBox.Items
.Select(item => item.ToString())
.OrderBy(x => x);
cartListBox.Items.Clear();
cartListBox.Items.AddRange(items);
cartListBox.Items.Count // is 0 length
you are doing in the previous step:
cartListBox.Items.Clear();
To add movieArray to listbox use AddRange
carListBox.Items.AddRange(movieArray);
To sort just set sorted =true
carListBox.Sorted=true;
Complete code is below
carListBox.Items.AddRange(movieArray);
carListBox.Sorted=true;
I'm sure the first response will be 'wtf, don't use arraylists!', but I'm really just trying to get this working in any way that I can.
It's basically the 'match looker' for a match 3 game. I'm having trouble getting access to the match data within the match list. See below..
public void FindAndRemoveMatches() {
ArrayList foundMatches = LookForMatches();
//just checking if we're getting the right amount for now
Debug.Log("We found " + foundMatches.Count + " 'Match 3's");
foreach(Object el in foundMatches){
// Debug.Log(el.ToString());
}
}
ArrayList LookForMatches(){
//List<int> matchList = new List<int>();
ArrayList matchList = new ArrayList();
// search for horizontal matches
// note that we're subtracting two rows here.
// We don't need to check the last two rows because we're matching 3.
for (int i = 0; i < BOARD_WIDTH; i++){
for (int j = 0; j < BOARD_HEIGHT-2; j++){
ArrayList match = GetMatchHoriz(i,j);
if (match.Count > 2) {
matchList.Add(match);
i += match.Count-1;
}
}
}
// search for vertical matches
for (int i = 0; i < BOARD_WIDTH; i++){
for (int j = 0; j < BOARD_HEIGHT-2; j++){
ArrayList match = GetMatchVert(i,j);
if (match.Count > 2) {
matchList.Add(match);
j += match.Count-1;
}
}
}
return matchList;
}
// look for horizontal matches starting at this point
ArrayList GetMatchHoriz(int col,int row){
ArrayList match = new ArrayList();
match.Add(mBoard[col,row]);
for(int i = 1; (col+i)<8; i++) {
if (mBoard[col,row] == mBoard[col+i,row]) {
if(mBoard[col+i,row] > mPieces.GetNumPieceTypes()) match.Add(mBoard[col+i,row]);
} else {
return match;
}
}
return match;
}
// look for horizontal matches starting at this point
ArrayList GetMatchVert(int col,int row){
ArrayList match = new ArrayList();
match.Add(mBoard[col,row]);
for(int i = 1; (row+i)<8; i++) {
if (mBoard[col,row] == mBoard[col,row+i]) {
if(mBoard[col,row+i] > mPieces.GetNumPieceTypes()) match.Add(mBoard[col,row+i]);
} else {
return match;
}
}
return match;
}
Good news is, I know that it's finding the matches correctly. The number of matches it's finding using the debug log correlates with what's happening on the screen. Yay! But, I need to get access to that data so I can compare it to the board (mBoard[col,row]) and remove those objects from the game board.
The 'foreach' loop in findandremovematches gives an error about casting. Any help with this?
thanks!
I hope i understand your question correctly
foreach(Objecct obj in list)
{
ArrayList inner = obj as ArrayList;
if(inner != null)
{
//this is what you are looking for
//you can then iterate the inner array list and get the int[,] you saved
}
}
However, as suggested, use List<ArrayList> or List<List<int[,]>> if I guessed it right.
If you're using ArrayLists because you think they're easier, don't. Use List.
If you're using ArrayLists because you have to and there is no way for you to use List (which I doubt) then you'll have something like this:
foreach(ArrayList innerList in foundMatches)
{
foreach(SomeClassThatYouAddToInnerLists item in innerlist)
{
//use item;
}
}
Replace SomeClassThatYouAddToInnerLists with whatever the type is that you're adding to the inner ArrayLists. (The type of mBoard.)
If you use Lists then it's very clear what the type is of everything inside of the list. A List<List<int>> is easy to work with. It's a list of lists of numbers.
i have lot of pictureboxes named this way: PBr1_1, PBr1_2, ... PBr1_9
I'd like to make loop
for (int i = 0; i < 10; i++)
{
if (Textbox.Text[i].ToString() == "1"){ "PBr1_"+"i".Tag = "cb.png";}
}
so for i=0 => PBr1_0, i=10 => Pbr1_10.
Example i have value in textbox: 0001011101 - then if value in textbox is "1" then i'd like to change picturebox tag.
How to automate this process, using for example loop "for"?
I suppose your controls are on a WinForm (this) and the ones with that name are all pictureboxes.
If so, that's the way ----
for (int i = 0; i < 10; i++)
{
if (Textbox.Text[i].ToString() == "1")
{
Control[] c = this.Controls.Find("PBr1_" + i.ToString(), true);
if(c != null && c.Length > 0) c[0].Tag = "cb.png";
}
}
You can put the picture boxes in to a List<PicutreBox> and iterate over the list.
var pictures = new List<PictureBox>();
pictures.Add(pic1);
pictures.Add(pic2);
//...
for (int i = 0; i < 10; i++)
{
if (Textbox.Text[i].ToString() == "1")
pictures[i].Tag = "cb.png";
}
Dynamic variable names as in your example are not supported.
Create an array (or list) that contain the picture boxes and use those within the for loop.
You can also use reflection but in my opinion it is best not to use that in this case.
If you are using WinForm you can use Control.Find method to locate a control by name
Once you have got the control you can easily change any property
I want to remove whole ListviewItems in my Listview except first Column. I have got a method but it sometimes throw ArgumentRangeException that i could not find why.
private void ListViewClear()
{
for (int i = 0; i < lstKullanicilar.Items.Count; i++)
{
if (lstKullanicilar.Items[i].SubItems.Count != 1)
{
lstKullanicilar.Items[i].SubItems.RemoveAt(1);
lstKullanicilar.Items[i].SubItems.RemoveAt(2);
lstKullanicilar.Items[i].SubItems.RemoveAt(3);
lstKullanicilar.Items[i].SubItems.RemoveAt(1);
lstKullanicilar.Items[i].SubItems.RemoveAt(1);
}
}
Try somethin like this:
for (int i = 0; i < lstKullanicilar.Items.Count; i++) {
while(lstKullanicilar.Items[i].Count > 1){
lstKullanicilar.Items[i].SubItems.RemoveAt(1);
}
}
The problem with your code is probably that you have a variable amount of items in the SubItems-collection. WIth the code you showed, you must at least have 6 items in the subitems-collection, for not getting an arugment exception.