C# 中的数组索引越界异常
本文关键字:越界 异常 索引 数组 | 更新日期: 2023-09-27 18:31:40
我有一组按钮,有48个。
在表单加载事件中,我从每个按钮中获取所有按钮文本值来运行查询,这是使用"for 循环和数组"完成的。
这是我迄今为止的工作。
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;
}
}
任何帮助,不胜感激。
for 循环不正确,您应该与长度<
而不是长度<=
进行比较:
for (int j = 0; j < btnarray.Length; j++)
{
Array
的索引从 0 到数组大小 - 1。将循环切换到
for (int j = 0; j < btnarray.Length; j++)
或
for (int j = 0; j <= btnarray.Length - 1; j++)
第一个选项更好,因为它每次迭代都会保存btnarray.Length - 1
计算。