这是我编写的从SQL Server获取数据并以标签显示数据的代码。 我的目标是在数据库中更改数据时获取数据,该值应通过仅刷新文本在标签中显示。没有特定数量的标签要添加到表单,标签的数量与数据库中的行成正比。 我正在动态创建标签,尽管出现了标签,但它们落后于上一个标签。
我想在出现新标签时清除以前的标签。
我做对了吗,哪里出了错?
private void timer1_Tick(object sender, EventArgs e)
{
string connectionstring = "Data Source=DESKTOP;Initial Catalog=DB;Integrated Security=True";
SqlConnection conn = new SqlConnection(connectionstring);
conn.Open();
//MySqlConnection con = new MySqlConnection(myconnectionstring);
string getdept = "SELECT tran_desc,sum(tran_qty) as qty FROM bill_tran group by tran_desc";
SqlCommand cmd = new SqlCommand(getdept, conn);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
adapter.Fill(dt);
for (int z = 0; z < dt.Rows.Count; z++)
{
//MessageBox.Show(x.ToString());
string nm = dt.Rows[z][0].ToString();
string qty = dt.Rows[z][1].ToString();
string getdept2 = "SELECT item,sum(qty) AS TotalQuantity FROM temp_dayin where item='" + nm + "' group by item";
System.Windows.Forms.Label txt = new System.Windows.Forms.Label();
this.Controls.Add(txt);
txt.Top = a * 28;
txt.Left = 12;
txt.Width = 600;
txt.Height = 25;
SqlCommand cmd2 = new SqlCommand(getdept2, conn);
SqlDataAdapter adapter2 = new SqlDataAdapter(cmd2);
DataTable dt2 = new DataTable();
adapter2.Fill(dt2);
string st = "";
for (int x = 0; x < dt2.Rows.Count; x++)
{
string nm2 = dt2.Rows[x][0].ToString();
string qty2 = dt2.Rows[x][1].ToString();
//MessageBox.Show(nm + qty + nm2 + qty2);
txt.Text = nm + qty2 + "-" + qty;
}
Controls.Add(txt);
a += 1;
}
}
private void Form3_Load(object sender, EventArgs e)
{
timer1.Start();
}
答案 0 :(得分:0)
可能是您可以做的,拥有一个面板并将所有标签添加到面板,在timer1_Tick
下,我们可以清除面板中的所有控件并可以重新添加新标签。
private void timer1_Tick(object sender, EventArgs e)
{
// clear all the controls under panel
panel.Controls.Clear();
// all your code to fetch the value from DB, and concatenate all
// required columns to make your desired value.
// set the label text as you value.
// add labels to panel
panel.Controls.Add(txt);
}
System.Windows.Forms.Panel panel = null;
private void Form3_Load(object sender, EventArgs e)
{
timer1.Start();
panel = new System.Windows.Forms.Panel();
this.Controls.Add(panel);
}