Account Unknown
Account Unknown

Reputation: 119

Array index out of bound exception in C#

I have a group of buttons like 48 of them.

In the form load event, I take all the button text values from each button to run a query, which is done using "for loop and array".

This is my work so far.

Button[] btnarray = { button1, button2, button3, button5, button6};

for (int j = 0; j <= btnarray.Length; j++)
{
    MySqlConnection con = new MySqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["db"].ConnectionString);
    con.Open();

    string query = "SELECT carplate FROM billing WHERE carplate='" + btnarray[j].Text + "' AND dates=DATE(NOW())"; // This is where i get error.

    MySqlCommand command = new MySqlCommand(query, con);

    var reader = command.ExecuteReader();

    if (reader.Read())
    {
        btnarray[j].BackColor = Color.Red;
    }
    else
    {
        btnarray[j].BackColor = Color.Khaki;
    }                
}

Any help is appreciated.

Upvotes: 0

Views: 601

Answers (2)

Guy
Guy

Reputation: 50909

The indexes of Array are from 0 to array size - 1. Switch the loop to

for (int j = 0; j < btnarray.Length; j++)

Or

for (int j = 0; j <= btnarray.Length - 1; j++)

First option is better since it saves the btnarray.Length - 1 calculation every iteration.

Upvotes: 0

Jens Meinecke
Jens Meinecke

Reputation: 2940

The for loop is incorrect you should compare to < the length not <= the length:

 for (int j = 0; j < btnarray.Length; j++)
    {

Upvotes: 1

Related Questions