问题描述
我需要创建一个表格,该表格将始终在 TableLayoutPanel 上显示 CTLog 的最后十条记录。因此,每当用户通过单击按钮在 Access 数据库中添加新的 CTLog 时,该表将动态更新并显示最后十个 CTLog。添加前十条记录时,我设法将它们放在表上,但无法显示在第 10 行之后添加的那些记录。我使用的方法是将TableLayoutPanel上的旧标签擦除,然后添加新标签。
private void RecentCT()
{
int j = 0;
for (j = 0; j < 10; j++)
{
tableLayoutPanel1.Controls.Remove(tableLayoutPanel1.GetControlFromPosition(j + 1,0));
tableLayoutPanel1.Controls.Remove(tableLayoutPanel1.GetControlFromPosition(j + 1,1));
}
string sql = "select Top 10 * from timer where ModelLog = @m and ShiftLog = @sl and ShiftStart = @ss and ShiftEnd = @se";
using (OleDbCommand cmd = new OleDbCommand(sql,connection))
{
//all cmd.Parameters.Add actions at here
try
{
connection.open();
//List<string> results = new List<string>(); I used list and foreach prevIoUsly
Label[] labels = new Label[10];
Label[] labels2 = new Label[10];
int i = 0;
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
labels[i] = new Label
{
Text = reader["CTLog"].ToString(),Anchor = AnchorStyles.None,Font = new Font("Microsoft Sans Serif",10,FontStyle.Regular),TextAlign = ContentAlignment.MiddleCenter
};
labels2[i] = new Label
{
Text = "Unit " + reader["UnitID"].ToString(),TextAlign = ContentAlignment.MiddleCenter
};
tableLayoutPanel1.Controls.Add(labels2[i],i + 1,0);
tableLayoutPanel1.Controls.Add(labels[i],1);
i++;
}
}
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Recent cycle time records cannot be retrieved. Error: " + ex.Message);
connection.Close();
}
}
}
我是否遗漏了什么或我的方法有什么问题?
解决方法
问题在于我使用的 sql 查询。 这是正确的 sql 查询:
string sql = "select top 10 * from timer where ModelLog = @m and ShiftLog = @sl and ShiftStart = @ss and ShiftEnd = @se ORDER BY ID DESC";
要获取最新的 10 行记录,我必须在查询中以 desc 形式组合 top 和 order by。因为只使用 top 关键字只会得到前 10 行,而不是后 10 行。