Index was outside the bounds of the array in CheckedListBox - c#

I am getting an index error on my else if statement but I'm unable to find the reason for it.
What I am doing is going through a CheckedListBox, if no values are checked print an error else show the selected values in a MessageBox.
Can anybody help me? Thank you!
for (int i = 0; i < checkedListBox1.Items.Count; i++)
if (checkedListBox1.CheckedItems.Count == 0)
{
Empty.SetError(checkedListBox1, "Please select at Least One");
return;
}
else if (checkedListBox1.GetItemChecked(i))
{
MessageBox.Show(checkedListBox1.CheckedItems[i].ToString());
}

Move the Count-ckeck before the loop:
if (checkedListBox1.CheckedItems.Count == 0)
{
Empty.SetError(checkedListBox1, "Please select at Least One");
return;
}
But the important part is that you are looping all items. Then you check for every item if it is checked with GetItemChecked. That's fine, but then you use checkedListBox1.CheckedItems[i] which doesn't contain all items but only the checked items. That's why you get the Index was outside the bounds error.
Instead you just need to use that collection instead of looping all:
for(int i = 0; i < checkedListBox1.CheckedItems.Count; i++)
{
MessageBox.Show(checkedListBox1.CheckedItems[i].ToString());
}

You should change
i < checkedListBox1.Items.Count;
To:
i < checkedListBox1.CheckedItems.Count;

checkedListBox1.CheckedItems[i] is the problem. You loop through all the items, but indexing CheckedItems. So when you have 10 items and checked 2nd item and 8th item, CheckedItems will have only two items but you'll be accessing CheckedItems[7] that's why you get the exception.
Use CheckedItems collection to access checked items directly.
if (checkedListBox1.CheckedItems.Count == 0)
{
Empty.SetError(checkedListBox1, "Please select at Least One");
return;
}
foreach (var checkedItem in checkedListBox1.CheckedItems)
{
MessageBox.Show(checkedItem.ToString());
}

Why are you checking for CheckedItems.Count inside the for cycle?
Take the first part of the If clause outside of the For cycle.
At the end your code can look like that:
if (checkedListBox1.CheckedItems.Count == 0)
{
Empty.SetError(checkedListBox1, "Please select at Least One");
}
for (int i = 0; i < checkedListBox1.Items.Count; i++)
if (checkedListBox1.GetItemChecked(i))
{
MessageBox.Show(checkedListBox1.Items[i].ToString());
}

Related

Check if Listbox contains a certain element

I know this question was posted here already multiple times but I've read the threads and nothing works for me so I decided to ask here.
I simply want to check if a certain string is already in my listbox. I've tried the
listBox.Items.Contains("stringToMatch")
but I get nothing.
I also tried
foreach (var item in form1.filterTypeList.Items)
{
if (item.ToString() == "stringToMatch")
{
break;
}
He doesn't find anything. Why? How can I solve that?
Try using this way... FindByText
strig toMatch = "stringToMatch";
ListItem item = ListBox1.Items.FindByText(toMatch);
if (item != null)
{
//found
}
else
{
//not found
}
Please try like below. I am doing for loop on List view items to search string based on item tag or item text.
for (int i = 0; i <= ListView.Items.Count - 1; i++)
{
itmX = ListView.Items.Item(i);
if (itmX.Text.ToString() = "stringToMatch")
{
break;
}
}
OR
for (int i = 0; i <= ListView.Items.Count - 1; i++)
{
itmX = ListView.Items.Item(i);
if (itmX.Tag.ToString() = "stringToMatch")
{
break;
}
}
its so simple now , you simply first find the index of that item in the collection of listbox items and then use this fuction of listbox listBox1.FindStringExact .
private void FindMySpecificString(string searchString)
{
// Ensure we have a proper string to search for.
if (searchString != string.Empty)
{
// Find the item in the list and store the index to the item.
int index = listBox1.FindStringExact(searchString);
// Determine if a valid index is returned. Select the item if it is valid.
if (index != ListBox.NoMatches)
listBox1.SetSelected(index,true);
else
MessageBox.Show("The search string did not find any items in the ListBox that exactly match the specified search string");
}
}
visit the following website for more clarification and examples
https://msdn.microsoft.com/en-us/en-en/library/81wes5yz(v=vs.110).aspx

How to remove multiple row from datagridview without using index?

I want to remove multiple row from datagridview,
I tried the below code, here row's are getting deleted based on index.
for (int m = 0; m < dataGridView3.Rows.Count - 1; m++)
{
if (dataGridView3.Rows[m].Cells[2].Value != null)
{
for (int n = 0; n < dataGridView2.Rows.Count - 1; n++)
{
if (dataGridView2.Rows[n].Cells[2].Value != null)
{
if (dataGridView2.Rows[n].Cells[2].Value.Equals(dataGridView3.Rows[m].Cells[2].Value) &&
dataGridView2.Rows[n].Cells[8].Value.Equals(dataGridView3.Rows[m].Cells[8].Value))
{
dataGridView2.Rows.RemoveAt(n);
//break;
}
}
}
}
}
here rows are not getting deleted properly, because index is changed after every single delete, so some records are missing out from loop.
can anyone help me how to solve this?
If you're going to remove items from the collection as you iterate through it like this, you'll need to work backwards through the collection of rows:
// start with the last row, and work towards the first
for (int n = dataGridView2.Rows.Count - 1; n >= 0; n--)
{
if (dataGridView2.Rows[n].Cells[2].Value != null)
{
if (dataGridView2.Rows[n].Cells[2].Value.Equals(dataGridView3.Rows[m].Cells[2].Value) &&
dataGridView2.Rows[n].Cells[8].Value.Equals(dataGridView3.Rows[m].Cells[8].Value))
{
dataGridView2.Rows.RemoveAt(n);
//break;
}
}
}
Alternatively, you could use LINQ to find your matches first, and then remove them:
var rowToMatch = dataGridView3.Rows[m];
var matches =
dataGridView2.Rows.Cast<DataGridViewRow>()
.Where(row => row.Cells[2].Value.Equals(rowToMatch.Cells[2].Value)
&& row.Cells[8].Value.Equals(rowToMatch.Cells[8].Value))
.ToList();
foreach (var match in matches)
dataGridView2.Rows.Remove(match);
Just to make it less of a maintenance head-ache, you might want to use the column name instead of the column index too... just a thought.

Return when a variable reach a certain value

I have an inventory which contains five slots. When adding an item to my inventory, I check for the best slot. If all slots are full, I want to display a line in the console and return out of the method, but I'm having trouble figuring that part out. I know that the value of best slot would only go from 0 to 4, but my if(bestSlot >= 4) isn't working right.
int bestSlot = -1;
for (int i = 0; i < PlayerInventory.Items.Count(); i++)
{
if (PlayerInventory.Items[i].ItemName == "empty")
{
if (bestSlot < 0)
{
bestSlot = i;
}
}
else if (PlayerInventory.Items[i].ItemName != "empty")
{
if (PlayerInventory.Items[i].ItemName == item.ItemName)
{
bestSlot = i;
}
}
}
// add now
if (bestSlot >= 4)
{
Console.WriteLine("inventory full");
return;
}
if (bestSlot >= 0)
{ //add the item }
Right now, the item isn't being added to the inventory but the code in the (bestSlot>= 0) is still being ran and I have an empty slot in my inventory when the console displays the line.
if (PlayerInventory.Items[4].ItemName != "empty" && PlayerInventory.Items[4].ItemName == item.ItemName)
{
Console.WriteLine("inventory full");
return;
}
On first read your question was not really clear, but I think you need this. You should delete for loop and everything in the loop bestSlot variable too. Right the needed code after this if.
Your problem is that you are going into all the elements of the PlayerIventory but you want to check only the 5. You can do this with the code which I show you.

Select items from a listbox through a loop?

I want to make it so that through a loop, it will select an item from the listbox. I was thinking about doing a for loop. This is (basically) what I want to accomplish:
for (int i = 0; i < lbRooms.Items.Count; i++)
{
lbRooms.Items.Select(i);
// do stuff here with the selected item
}
I know thats not how it works, but I want it to do it like that. I appreciate all the help, thanks =D
EDIT: I think this will work, but I'm sure it can be improved:
for (int i = 0; i < lbRooms.Items.Count; i++)
{
lbRooms.SetSelected(i, true);
}
Try:
lbRooms.setSelected(i, true);
instead of:
lbRooms.Items.Select(i);
You can't select your items like that, You can use indexer to get your item:
for (int i = 0; i < lbRooms.Items.Count; i++)
{
var currentItem = lbRooms.Items[i];
}
If you want to select that item you can set Selected property to true:
currentItem.Selected = true;
foreach (listitem item in lbRooms.Items)
//do item manipulation here

Loop thru the combobox and compare with the data in the database

i had try several method to loop through the combobox, but it won't work...
for (Int16 i = 0; cbxrecipe.Items.Count - 2 >= i; i++)
{
if (cbxrecipe(i).Items.ToString() != Reader_recipe1.GetValue(0).ToString())`
{
//update the combobox;
}
}
means i need to loop through the combobox, to check whether the items inside the combobox is same with the data in the database, if same, it will not update, otherwise, the combobox will appear new item immediately...
thanks for the help =)
you have an error in your code.
try this :
for (Int16 i = 0; cbxrecipe.Items.Count - 2 >= i; i++)
{
if (cbxrecipe.Items[i].ToString() != Reader_recipe1.GetValue(0).ToString())
{
//update the combobox;
}
}

Categories

Resources