Search code examples
c#databaselabelautocreate

C# data from database to label


EDIT: I decided to write this post again.

I have problem with autocreate labels from database.

This is what i wrote [NEW CODE] :

    public partial class Form1 : Form
    {

    int i = 0;
    int r = 0;
    int c = 0;

    int x = 22;
    Label[] lbl1 = new Label[25];


    public Form1()
    {
        InitializeComponent();
    }




    private void button1_Click(object sender, EventArgs e)
    {
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConString"].ConnectionString);

        string Worker_names = "SELECT Worker_Name, Worker_SName FROM Workers";
        SqlCommand cmd = new SqlCommand(Worker_names, conn);
        cmd.Connection = conn;
        SqlDataAdapter sdadapter = new SqlDataAdapter(cmd);
        DataTable DataTable1 = new DataTable();
        sdadapter.Fill(DataTable1);

        conn.Open();

                foreach (DataRow row in DataTable1.Rows)
                {

                    DataTable1.Rows[r].ToString();
                    string getValue = cmd.ExecuteScalar().ToString();

                    if (getValue != null)
                    {
                        lbl1[i].Text = getValue;
                        lbl1[i].Location = new System.Drawing.Point(60, x);
                        lbl1[i].Font = new System.Drawing.Font("Microsoft Sans Serif", 9F,
                                    System.Drawing.FontStyle.Bold,
                                    System.Drawing.GraphicsUnit.Point,
                                    ((byte)(0)));
                        lbl1[i].BackColor = Color.LightBlue;

                        panel1.Controls.Add(lbl1[i]);
                        panel1.AutoSize = true;
                        panel1.Show();
                        panel1.Refresh();

                        i++;
                        r++;
                        c++;
                        x = x + 30;
                    }
                    else
                        MessageBox.Show("End");
              }
              conn.Close();
         }
    }

Error is in this line when program read loop second time:

     lbl1[i].Text = getValue;

     NullReferenceException was unhandled

So maybe now is better. Can you help me ?


Solution

  • Label[] lbl1 = new Label[25];
    

    should really be

    Label[] lbl1 = new Label[DataTable1.Rows.Count];
    

    AND you need to do

    lbl1[I] = new Label(..)
    

    before you call

    lbl1[I].Text = ...`