Question

In this conditional statement I have tried the last portion in order to try and execute a section of code if my Form Collection is empty.

if ((myDT == null) || (myCollection.GetKey(0).ToString() == "heatSearch") || (myCollection == null))
{
    //some code here
}

Each time I run the code and the Form Collection is empty, at which time this condition should be true, my application crashes and I receive this error: Index was out of range. Must be non-negative and less than the size of the collection.

Some more information...this check is being performed in an ActionResult called by an AJAX post. The post is what fails and returns the error at this line shown here: <b> Source File: </b> c:\Users\D\Documents\Visual Studio 2012\Projects\TheMProject(1)\TheMProject\Models\HomeModel.cs<b> &nbsp;&nbsp; Line: </b> 936

Line 936 is the one with the if.

Was it helpful?

Solution

Fix it:

if ((myDT == null) || (myCollection == null) || (myCollection.GetKey(0).ToString() == "heatSearch"))
{
    //some code here
}

You're calling myCollection.GetKey(0) before test if myCollection is null.

OTHER TIPS

Have you tried...

public ActionResult MyAction(FormCollection f)
{
    if (f.Count == 0)
        {
            Debug.WriteLine("Hello");
        }

        return View();
}
if ((myDT == null) || (myCollection == null) || (myCollection.Count > 0) )
{
    //some code here
}

is what I'd do

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top