I have an if statement saying that if a webpage has a certain text to remove the selected item on a listBox and iterate down to the next one.
I made some code but when I try it I keep getting:
ArgumentOutOfRangeException was unhandled by usercode
This is the error in more detail:
{"InvalidArgument=Value of '1' is not valid for
'SelectedIndex'.\r\nParameter name: SelectedIndex"}
This is my code:
listBox1.Items.Remove(listBox1.SelectedItem);
listBox1.SelectedIndex = + 1;
EDIT:
Thanks for all the help guys! I removed the issue by not removing the items and just making it iterate down.
You have to test if the item which you are trying to select acutally exists.
int index = listBox1.SelectedIndex;
listBox1.Items.RemoveAt(index);
If (index < listBox1.Items.Count) {
listBox1.SelectedIndex = index;
}
EDIT: If you want to delete items in a loop, it is a good idea to start at the end, since removing an item changes the position of the following items. Looping upwards would make you skip an item each time you remove an item.
for (int i = listBox1.Items.Count - 1; i >= 0; i--) {
if (listBox1.Items[i].ToString() == "whatever") {
listBox1.Items.RemoveAt(i);
}
}
I'd have to see the full code sample (with the if statement) to know for sure. But it is pretty obvious you are setting the selected item to an index that isn't in the list box.
Be careful, the selectedIndex is zero based, not one based.
MSDN says of your error:
ArgumentOutOfRangeException: The assigned value is less than -1 or
greater than or equal to the item count.
Since the error indicates it is happening when you set the SelectedIndex to 1, I am assuming that you only have a single item in the listbox (index=0) when this code is called.
Since indices are 0-based, setting SelectedIndex to 1 is selecting the second value in the list. I'm guessing it's failing when you have removed all but one of the values and are trying to set SelectedIndex to the second one.
Do you want to select the first item in the listBox? If so the code would be:
if(listBox1.Items.Count > 0) listBox1.SelectedIndex = 0;
Related
I have several items in my ComboBox. But how to tell ComboBox to show only item number 1 from list as default? Currently at design time I have empty text.
You have to set SelectedIndex:
comboBox.SelectedIndex = 1;
You can use the SelectedIndex as show value:
comboBox1.SelectedIndex = 0;
NB: you should check the count of values in your Items array.
MS documentation: https://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.selectedindex(v=vs.110).aspx
I have a listbox control on winform and same is Single Items SelectionMode OR One Items Selection Mode. I am trying to scroll it from form_KeyDown Event as below
if ((Keys)e.KeyCode == Keys.Down)
{
if (listBox2.Items.Count >= listBox2.SelectedIndex)
{
listBox2.SelectedIndex++;
}
}
But it’s throw an error like “ArgumentOutOfRangeException was unhandled”
Invalid argument of value =23 is not valid for selection index.
How to get ridoff?
Try this:
if ((Keys)e.KeyCode == Keys.Down)
{
if ((listBox2.Items.Count-1) > listBox2.SelectedIndex)
{
listBox2.SelectedIndex++;
}
}
Remember that if you have 23 items, SelectedIndex goes from 0 to 22...
ListBox.SelectedIndex is a zero based array IE the first item will be 0 in the index whereas the Items.Count will always return a value starting at 1.
Please see the following for further information:
http://msdn.microsoft.com/en-us/library/system.windows.forms.listbox.selectedindex.aspx
Kind Regards, Wayne
According to MSDN's documentation on ListBox.SelectedIndex:
A zero-based index of the currently selected item. A value of negative
one (-1) is returned if no item is selected.
So, I believe you need to change
if (listBox2.Items.Count >= listBox2.SelectedIndex)
to
if (listBox2.Items.Count-1 > listBox2.SelectedIndex)
Please vote Marco's answer as correct, as he pointed this out to me!
Because if there are 23 items in the listbox, item 23 is actually item 22, item 1 is actually item 0, etc. etc.
I have a for loop that for each item in a listbox it will perform a sub. Whats weird is the for loop didnt iterate at all. I had to force it to iterate to the first item but after if finished performing all the subs for that item it just stopped.
How can I make it keep iterating for each item in the listbox?
Heres my code:
listBox7.SelectedIndex = 0;
for (int i = 0; i < listBox7.Items.Count; i++)
{
sub1();
sub2();
listBox1.Items.Add(listBox7.SelectedItem.ToString() + "\r");
while (listBox7.SelectedItems.Count > 0)
{
listBox7.Items.Remove(listBox7.SelectedItems[0]);
}
webBrowser1.Navigate("http://www.google.com");
}
You are most likely removing all of the items in the inner while statement, leaving nothing to iterate on in the second pass.
If your listBox1 contains more than 1 item, an exception will always be thrown on the following line:
listBox1.Items.Add(listBox7.SelectedItem.ToString() + "\r");
because there is no longer a selected item.
This is why exception handling, even if you are just testing something, is critical.
If your goal is to process every item in listBox7, then you can accomplish this by moving the following line:
listBox7.SelectedIndex = 0;
inside the for loop, above the line
sub1();
I'm trying to remove all users from an AD group with the following code:
private void RemoveStudents() {
foreach (DirectoryEntry childDir in rootRefreshDir.Children) {
DirectoryEntry groupDE = new DirectoryEntry(childDir.Path);
for (int counter = 0; counter < groupDE.Properties["member"].Count; counter++) {
groupDE.Properties["member"].Remove(groupDE.Properties["member"][counter]);
groupDE.CommitChanges();
groupDE.Close();
}
}
}
The rootRefreshDir is the directory that contains all the AD groups (childDir).
What I'm finding here is that this code does not behave correctly. It removes users, but it doesn't do it after the first run. It does "some". Then I run it again, and again, and again - depending on how many users need to be deleted in a group. I'm not sure why it's functioning this way.
Can someone help fix this code or provide an alternative method to delete all users in a group?
You're looping through the items as you delete them causing the index to skip every other item.
You need to change the inner for loop to loop backwards, like this:
PropertyValueCollection members = groupDE.Properties["member"];
for (int counter = members.Count - 1; counter >= 0; counter--) {
members.RemoveAt(counter);
groupDE.CommitChanges();
groupDE.Close();
}
Your problem is that you're counting upwards... You first remove an item at index 0. Every remaining item then moves to index - 1 in the list. You then remove at index 1, and every remaining item shuffles except for the one you've now left at index 0. Basically: you're only removing half of the items.
Instead of a for loop, try while (groupDE.Properties["member"].Count > 0), and simply remove the item at index 0 each time.
Or if you are using
DirectoryServices.AccountManagement.GroupPrincipal (.NET 3.5+):
This will work as well:
groupPrincipal.Members.Clear();
groupPrincipal.Save();
just use:
group.Properties["member"].Clear();
group.CommitChanges();
This reference in CodeProject should help:
"How To Do (almost) Everything in AD:
http://www.codeproject.com/KB/system/everythingInAD.aspx
I'm hoping someone can help with an exception I've inherited. Basically I'm writing the rows in a datagrid to a text file. Which works fine apart from when the row is hidden, when the row is hidden the exception "Index was outside the bounds of the array" is thrown at the line highlighted below. Thanks for any help.
DataRow dr;
for (int i = 0; i < bindingManagerBase.Count; i++)
{bindingManagerBase.Position = i;
dr = ((DataRowView)bindingManagerBase.Current).Row;
bindingManagerBase.SuspendBinding();
try
{
int rowIndex = dr.Table.Rows.IndexOf(dr);
if (!rowsDisplayStatus[rowIndex]) //<---------Exception here "Index was outside the bounds of the array" //Picture below
{
m_Dgv.Rows[rowIndex].Visible = false;
continue;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
finally
{
bindingManagerBase.ResumeBinding();
}
writeData(tw, dr);
iIndex++;
}
You're getting the row index and then trying to use it with rowsDisplayStatus. You can't use the database row index as an index into your collections.
I would change:
if (!rowsDisplayStatus[rowIndex])
to:
if (!rowsDisplayStatus[i])
How is rowsDisplayStatus populated? If it only contains one element and something is expected to be at index 9, you should take a look at the code that populates it.
As the picture shows, rowsDisplayStatus has 1 item in it... you're trying to pull the 10th item (or the item at index 9)... that index is out of range.
How is "rowsDisplayStatus" populated? Maybe there is a problem in that routine.
I'll explain what mark said, above. (Don't know how to comment, so putting this in an answer)
He's correct you should change the
if (!rowsDisplayStatus[rowIndex])
Into
if (!rowsDisplayStatus[i])
The reason for this is as follows:
The rowIndex grows even when rows where previously deleted from the Rows object. So there could be only one or two rows in the dr.Table.Rows, but they could have indexes (indice) for example of 8 and 9 (because previously rows 1 to 7 where erased or for other reasons).
So you get the current rowIndex by checking the bindingManager.Current.RowIndex property.
But your rowsDisplayStatus is a simple array (or ArrayList) with the correct amount of rows according to i. So for row index:8 (the first row) you should look at rowsDisplayStatus[0] (which is the value of i), and for row index:9 (the second row) you should look at rowsDisplayStatus[1]... etc.
HTH, Moshe
Basically, whenever I've received this error the index (or value that I have set) was non-existant at the time it was being referenced.
For example if I have two Items in a ListBox and I tryi to reference a third Item, I will receive an Index Out Of Range exception (many times in the past)...