从数据库到标签的C#数据
本文关键字:数据 标签 数据库 | 更新日期: 2023-09-27 18:24:22
编辑:我决定再写一次这篇文章。
我对从数据库自动创建标签有问题。
这是我写的[新代码]:
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
所以也许现在更好。你能帮我吗?
Label[] lbl1 = new Label[25];
应该是
Label[] lbl1 = new Label[DataTable1.Rows.Count];
你需要做
lbl1[I] = new Label(..)
在你打电话给之前
lbl1[I].Text = ...`