I'm constantly getting the same error.
An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in System.Windows.Forms.dll
Additional information: InvalidArgument=Value of '0' is not valid for 'index'.
The Code is:
private void radGridView1_CellFormatting(object sender, Telerik.WinControls.UI.CellFormattingEventArgs e)
{
if (e.CellElement.ColumnInfo.HeaderText == "logo")
{
if (e.CellElement.RowInfo.Cells[2].Value.ToString() == "Error")
{
e.CellElement.Image = (Image)imageList1.Images[0];
e.CellElement.ToolTipText = "Error";
}
else if (e.CellElement.RowInfo.Cells[2].Value.ToString() == "Warning")
{
e.CellElement.Image = imageList1.Images[1];
e.CellElement.ToolTipText = "Warning";
}
else if (e.CellElement.RowInfo.Cells[2].Value.ToString() == "Message")
{
e.CellElement.Image = imageList1.Images[2];
e.CellElement.ToolTipText = "Message";
}
}
}
}
//-----------------------------------------------------------------------
MSDN says this
The exception that is thrown when the value of an argument is outside the allowable range of values as defined by the invoked method.
about the ArgumentOutOfRangeException. It goes on to say that
You are retrieving the member of a collection by its index number, and the index number is invalid.
This is the most common cause of an ArgumentOutOfRangeException
exception. Typically, the index number is invalid for one of three
reasons:
The collection has no members, and your code assumes that it does.
You're attempting to retrieve an item whose index is negative. This
usually occurs because you've searched a collection for the index of a
particular element and have erroneously assumed that the search is
successful.
You're attempting to retrieve an element whose index is equal to the
value of the collection's Count property.
My suspicion is that it's the first case here, i.e. imageList1 is empty. So your imageList1.Images[0] throws the exception because there is nothing there.
To determine if this is the case try imageList1.Images.Count. Given you're looking at 3 elements in your code Count must be >= 3.
From the looks of it, you don't have anything in the array. Do a check to see if the indices are actually initialized, and then go on from there.
Related
I sometimes run into situations where, if a line of code throws an exception, I don't care what the exception is or why it was thrown; I just need to take a generic action and move on. For example:
try
{
// Throws IndexOutOfRangeException when DB field
// is null in the current record
Template = record.GetString(MYSQL_IDX_TEMPLATE);
}
catch
{
Template = FIELD_UNAVAILABLE;
}
I was wondering if there's a short-hand way to set a value based on a generic try/catch?
I'm thinking of something similar to ternary syntax:
string blah = (index >= ubound ? "No more records" : "records exist");
I am getting the error at getProxy(), the error is index outofbounds.
Error:
An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll
Additional information:
Index was out of range. Must be non-negative and less than the size of the collection.
Code:
static List<String> proxies = new List<String>();
private static String getProxy()
{
lock (proxies)
{
return proxies[new Random().Next(0, proxies.Count)];
}
}
It is not empty, has a proxy inside, the error is not in my loading function, it is here.
I have added a breakpoint and debugged it, proxies has the value of Count = 3 and proxies.count has the value of 3.
The answer from #Gendolkari:
If proxies contains no elements at all, then it would be trying to
access the first element of an empty list and throw this exception.
return proxies[new Random().Next(0, proxies.Count)];
==>
return proxies[new Random().Next(0, 0)];
==>
return proxies[0];
This causes an ArgumentOutOfRangeException as stated in the documentation for List(T).Item because proxies is empty.
I have this code today:
MyListView.Items[index].Selected = true;
And I want to control that the value of index is valid. How do I check within the ListViewItemCollection if that element exists?
You would have to check if index is within the range of the collection before trying to access it if you do not wish for an IndexOutOfRangeException to be thrown.
This can be done something like this:
if (index < MyListView.Items.Count()){
MyListView.Items[index].selected = true;
} else {
// handle the index being outside the collection
}
I have the following method that checks if I have object in the first index and add to it if empty
private void GetRestriction(TableRow[] RistrictionsArgs)
{
var restrictionList = new List<Restriction>();
foreach (var restriction in RistrictionsArgs)
{
var Id = int.Parse(restriction.Values.ElementAt(1));
var test = restrictionList[Id - 1];
if (test == null)
{
restrictionList[Id - 1] = new Restriction()
{
SequenceID = Id.ToString(),
};
test = restrictionList[Id - 1];
}
}
}
The problem I am having is when it reaches the line var test = restriction[Id-1]; it throws 'Index was out of range. Must be non-negative and less than the size of the collection.'
What am I missing? how can check the first element is empty and then add element to it?
No items exist in restrictionList (the length is 0), so trivially restrictionList[anyIndex] is invalid and will throw the reported exception. Lists do not automatically grow on an index operation.
To check if the the collection is empty, use restrictionList.Length == 0 (or other check as appropriate to see if a particular Id is in range). Then use Add to add a new element - not another index which will also throw an exception for the same reason as above.
Showing the actual ID's and explaining the algorithm and expected result will likely lead to better answers, as the above notes say what is currently wrong, and not necessarily "how write it correctly".
Random r = new Random();
int InvadorNumberA=r.Next(0,5);
int randomShot = r.Next(5);
List<Invaders> invadersShooting = new List<Invaders>();
Invaders invaderA=new Invaders();
var invaderByLocationX = from invadersSortByLocation in invaders
group invadersSortByLocation by invadersSortByLocation.Location.Y
into invaderGroup
orderby invaderGroup.Key
select invaderGroup;
invadersShooting = invaderByLocationX.Last().ToList();
try
{
invaderA = invadersShooting[InvadorNumberA];// constantly being thrown there. i cant catch the exception.. so i guess it is being thrown somewhere else. any idea on how i stop it from being thrown?
}
catch(ArgumentOutOfRangeException dd)
{
invaderA = invadersShooting[0];
}
stack Trace
" at System.ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource)\r\n at System.ThrowHelper.ThrowArgumentOutOfRangeException()\r\n at System.Collections.Generic.List`1.get_Item(Int32 index)\r\n at WindowsFormsApplication1.Game.ReturnFire() in D:\Documents and Settings\Dima\My Documents\Visual Studio 2008\Projects\SpaceInvaders\SpaceInvaders\SpaceInvadorGame\Game.cs:line 444"
Target Site
{Void ThrowArgumentOutOfRangeException(System.ExceptionArgument, System.ExceptionResource)}
More info:
{"Index was out of range. Must be non-negative and less than the size of the collection.\r\nParameter name: index"}
{"Index was out of range. Must be non-negative and less than the size of the collection.\r\nParameter name: index"}
i got rid of the exception by simply doing this
invadersShooting = invaderByLocationX.Last().ToList();
invaderA = invadersShooting[r.Next(0,invadersShooting.Count)];
but i am still curious,,on where the exception was thrown..hmmm
Don't do this.
Exceptions should be exceptional. You have every means to prevent this exceptional scenario and you absolutely should.
invaderA = invadersShooting[InvadorNumberA];
invaderA = invadersShooting[0];
In the first case, InvadorNumberA can be anything from 0 to 4. Check and see whether the list has at least InvadorNumberA + 1 elements in it before trying to get an element from it. Do not rely upon an exception to correct your course. More than that, perhaps InvadorNumberA should actually be constrained to random.Next(0, list.Count). Why create a number from 0 to 4 when there may only be 1 or 2 elements in the list?
It could be thrown again in you catch block, as it is not guaranteed that the size of the list is at least 1 there.
If invadersShooting is the empty list you will get an exception thrown in the try handler. You will catch this exception in the catch handler. However, you then once more index into the empty list and a new exception is thrown, this time in the catch handler. That exception is not caught and you have an unhandled exception.
Simply inspect invadersShooting.Count before trying to get an element.