简体   繁体   中英

Array Index Is Out of Bounds

I have this method that checks a row based on what's in it. I also have a static string array that is initialized with nothing in it. I'm getting an out of bounds index error which doesn't make any sense to me because I don't have a max length on the array.

private void PrintTable(DataTable table)
{ 
    foreach (DataRow row in table.Rows)
    {
        litCanCount.Text = "Canoe count is: ";
        litKayCount.Text = "Kayak count is: ";

        string currRow = row["CraftType"].ToString();
        if (currRow == CANOE)
        {
            Response.Write("CANOE INCREMENT!<br />");
            CANOEi++;
            txtCanCount.Text = CANOEi.ToString();
            arr[i] = currRow;
            i++;
        }
        if (currRow == KAYAK)
        {
            Response.Write("KAYAK INCREMENT!<br />");
            KAYAKi++;
            txtKayCount.Text = KAYAKi.ToString();
            arr[i] = currRow;
            i++;
        }
        for (int a = 0; arr.Length > a; a++)
        {
            Response.Write(arr[a] + "<br />");
        }
    }
}

public partial class Index: System.Web.UI.Page
{
    string CANOE = "Canoe";
    string KAYAK = "Kayak";
    int CANOEi;
    int KAYAKi;
    string[] arr = new string[] { };
    int i = 0;
}

I don't think that you need that code. If you just want to show the count of canoe and kayak you could use an elementary call to Select

    DataRow[] canoe = table.Select("CraftType = 'Canoe'");
    DataRow[] kayak = table.Select("CraftType = 'Kayak'");

    litCanCount.Text = "Canoe count is: " + canoe.Length;
    litKayCount.Text = "Kayak count is: " + kayak.Length;

If you think about it, a datatable is just a sophisticated array and the framework offers many methods to work with a datatable.

For example, in LINQ

int canoeNumber = table.AsEnumerable().Count(x => x["CraftType"].ToString() == "Canoe");

Arrays must be assigned a length

Array with zero length (Runtime exception)

static void Main()
{
    string[] arr = new string[] { }; //Array with no length
    arr[0] = "hi"; //Runtime exception
}

Array with one length (No exceptions)

static void Main()
{
    string[] arr = new string[1]; //Array with one length, index starts at zero
    arr[0] = "test";
}

If you want to use a collection without defining the size then consider using a list

List Collection (no length definition needed)

   List<string> listString = new List<string>();
   listString.Add("hi");
   listString.Add("bye");
   listString.Add("oh hai");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM