I want to generate dynamic labels with its text fetched through database. I am getting this error "Index was outside the bounds of the array."
at line l.Name = split[j] + i.ToString();
I want to display 5 labels. There are 5 records in array that I am fetching through database and I want to display each record on each label. I cant figure out what is wrong with this code. Help me out. I have used split function to split the array.
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;
}
Any suggestion what can I do?