编辑: 我决定再次写这篇文章。
我在使用数据库中的自动创建标签时遇到问题。
这就是我写的[新代码]:
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
所以也许现在更好。你能救我吗?
答案 0 :(得分:0)
Label[] lbl1 = new Label[25];
应该是
Label[] lbl1 = new Label[DataTable1.Rows.Count];
你需要做
lbl1[I] = new Label(..)
之前打电话
lbl1[I].Text = ...`