-1

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?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Ashwini Nemade
  • 153
  • 1
  • 13

3 Answers3

3

you are having error here

for (int j = 0; j <= split.Length; j++)
{
    Label l = new Label();
    l.Name = "label" + i.ToString();
    l.Text = split[j] + i.ToString();
}

you have to make it

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

If you have 5 elements the split.Length give you 5. but it is stored in index 0 to 4. If you are giving j <=split.Length it work from j=0 to j=5. and split[5] give you this error

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Jinto Jacob
  • 385
  • 2
  • 17
1

As the other answers suggests, changing the condition in the loop will solve your issues. but the real issues comes after that only. you have to care about the following things as well for making your code better.

  • Using concatenated string as queries is like giving your locker key to the hacker. better to use parameterization.
  • for the first case you are using the subjects field and second case you are using the smarks field only, they why are you fetching the whole things using *. always get only required fields from the database.
  • Make use of using statements for automatic disposal of objects.
  • As per this implementation the method addlabel need not to return anything, you can create and add dynamic labels within the method itself.

Your code will be like the following, which includes all changes that i mentioned here

void addlabel(int i, int start, int end)
{
    string conStr = ConfigurationManager.ConnectionStrings["dbx"].ConnectionString;
    using (SqlConnection conObject = new SqlConnection(conStr))
    {
        conObject.Open();
        string querySql = "SELECT subjects FROM marks  WHERE idno like @idInputs";
        using (SqlCommand cmdSql = new SqlCommand(querySql, conObject))
        {
            cmdSql.Parameters.Add(" @idInputs", SqlDbType.VarChar).Value = "%" + textBox1.Text + "%";
            using (SqlDataReader reader = cmdSql.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 newLabel = new Label();
                        newLabel.Name = "label" + i.ToString();
                        newLabel.Text = split[j] + i.ToString();
                        this.Controls.Add(newLabel);
                     }
                }
            }
        }
    }
}
sujith karivelil
  • 28,671
  • 6
  • 55
  • 88
0

Your problem is that your for loop loops one time to many. If you have 3 elements in split, you'll loop from 0 to 3 which is 4 times.

Change the for loop to

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

to loop the right number of times

Hans Kilian
  • 18,948
  • 1
  • 26
  • 35