【发布时间】:2018-06-29 05:38:38
【问题描述】:
我想生成动态标签,其文本通过数据库获取。我在l.Name = split[j] + i.ToString(); 行收到此错误"Index was outside the bounds of the array."
我想显示 5 个标签。我通过数据库获取数组中有 5 条记录,我想在每个标签上显示每条记录。我无法弄清楚这段代码有什么问题。帮帮我。我已经使用 split 函数来拆分数组。
private void button1_Click(object sender, EventArgs e)
{
int start = 232;
int end = 100;
for(int i=0;i<5;i++)
{
Label l = addlabel(i, start, end);
this.Controls.Add(l);
end += 30;
}
int start1 = 353;
int end1 = 100;
for (int i1 = 0; i1 < 5; i1++)
{
Label l = addlabel1(i1, start1, end1);
this.Controls.Add(l);
end += 30;
}
}
Label addlabel(int i,int start,int end)
{
string cons = ConfigurationManager.ConnectionStrings["dbx"].ConnectionString;
SqlConnection con = new SqlConnection(cons);
con.Open();
string str = "SELECT * FROM marks WHERE idno like '%" + textBox1.Text + "%'";
SqlCommand com = new SqlCommand(str, con);
SqlDataReader reader = com.ExecuteReader();
while (reader.Read())
{
var input = reader["subjects"].ToString();
var split = input.Split(new string[] { ",", " " }, StringSplitOptions.RemoveEmptyEntries);
for (int j = 0; j <= split.Length; j++)
{
Label l = new Label();
l.Name = "label" + i.ToString();
l.Text = split[j] + i.ToString();
}
}
return label1;
}
Label addlabel1(int i1, int start1, int end1)
{
string cons = ConfigurationManager.ConnectionStrings["dbx"].ConnectionString;
SqlConnection con = new SqlConnection(cons);
con.Open();
string str = "SELECT * FROM marks WHERE idno like '%" + textBox1.Text + "%'";
SqlCommand com = new SqlCommand(str, con);
SqlDataReader reader = com.ExecuteReader();
while (reader.Read())
{
var input1 = reader["smarks"].ToString();
var split1 = input1.Split(new string[] { ",", " " }, StringSplitOptions.RemoveEmptyEntries);
for (int z = 0; z <= split1.Length; z++)
{
Label l = new Label();
l.Name = "label" + i1.ToString();
l.Text = split1[z] + i1.ToString();
}
}
return label1;
}
有什么建议吗?
【问题讨论】:
-
一个建议:停止连接 SQL 查询,改用参数。查找 SQL 注入
-
调试你的代码,尤其是在你循环分割字符串的地方。观察你试图访问的索引