-6

编辑:我决定再次写这篇文章。

我从数据库自动创建标签有问题。

这就是我写的[新代码]:

    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();
         }
    }

第二次程序读取循环时,此行出现错误:

     lbl1[i].Text = getValue;

     NullReferenceException was unhandled

所以也许现在更好。你能帮助我吗 ?

4

1 回答 1

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

真的应该

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

你需要做

lbl1[I] = new Label(..)

在你打电话之前

lbl1[I].Text = ...`
于 2014-09-25T19:06:17.090 回答