Reputation: 1070
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.
This is my method:
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 />");
}
}
}
This is the top piece of my class, with my static variables:
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;
}
Upvotes: 0
Views: 778
Reputation: 2052
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");
Upvotes: 1
Reputation: 216273
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");
Upvotes: 2