How to rectify Exception 'Index Out of Range'

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ajinkya ragalwa
    New Member
    • Feb 2011
    • 14

    How to rectify Exception 'Index Out of Range'

    Hey guys,


    I am making an application that generates 'ID'
    automatically. Let me post part of my code for ya all.



    Code:
    dt = dB1DataSet1.Tables["company"];
                len = dt.Rows.Count + 1;
                dr = dt.Rows[len];
                code = dr["C_ID"].ToString();
                cde = code.Substring(1, 2);
                ctr = Convert.ToInt32(cde);
    
                    if ((ctr >= 1) && (ctr < 9))
                    {
    
                        ctr = ctr + 1;
    
                        textBox1.Text = "C00" + ctr;
    
    
    
                    }
                    else if ((ctr >= 9) && (ctr < 99))
                    {
                        ctr = ctr + 1;
                        textBox1.Text = "C0" + ctr;
                    }
                    else if (ctr >= 99)
                    {
                        ctr = ctr + 1;
                        textBox1.Text = "C" + ctr;
                    }


    here company is table where i have C_ID column.
    Every time i try to run this code it gives me error
    in line : dr = dt.Rows[len] Error : "Make sure that maximum index on the list is less than the list size".
    And also the 'ID' that is getting generated is not being displayed in text box. So do have any suggestions about how do i do it?


    Thanks
    ajinkya
  • GaryTexmo
    Recognized Expert Top Contributor
    • Jul 2009
    • 1501

    #2
    For the first issue, the error tells you exactly what you need to know. You're trying to access an index in the array that doesn't exist. Here are the offending lines...

    Code:
    len = dt.Rows.Count + 1;
    dr = dt.Rows[len];
    Arrays in C# are 0-indexed, which means the first element in every array is at index 0. You've requested the count for your array, then you even add one to it. The best way to envision this is to just make up numbers and then run through the code.

    Lets say your array had a count of 10. This would mean you would have indexes 0 through 9 available and containing data. Your code calculates len as count + 1 = 10 + 1 = 11. You're trying to access index 11 when it doesn't exist. Your code should actually be...

    Code:
    len = dt.Rows.Count - 1;
    dr = dt.Rows[len];
    For the second issue, why the value doesn't show up in the textbox, it looks like ctr governs this. You've got an if-then-else-if statements with no else clause, so it's possible to execute through your code and not have the textbox get set. The most likely candidate here is that ctr is evaluating to zero, but perhaps it's another number outside your range. Put a breakpoint on that line and step through to see what it's getting.

    Comment

    Working...