0

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.

1
  • 1
    SQL Injection alert - you should not concatenate together your SQL statements - use parametrized queries instead to avoid SQL injection Commented Jan 24, 2016 at 8:58

2 Answers 2

1

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

 for (int j = 0; j < btnarray.Length; j++)
    {
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.