首页 > 解决方案 > TableLayoutPanel 不显示最后 10 行数据

问题描述

我需要创建一个表格,该表格将始终在 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(),
                                Anchor = AnchorStyles.None,
                                Font = new Font("Microsoft Sans Serif", 10, FontStyle.Regular),
                                TextAlign = ContentAlignment.MiddleCenter
                            };
                            tableLayoutPanel1.Controls.Add(labels2[i], i + 1, 0);
                            tableLayoutPanel1.Controls.Add(labels[i], i + 1, 1);
                            i++;
                    }
                }
                connection.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Recent cycle time records cannot be retrieved. Error: " + ex.Message);
                connection.Close();
            }

        }
    }

我的方法是否遗漏了什么或有什么问题?

标签: c#winformsms-accesstablelayoutpanel

解决方案


问题出在我使用的 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 行。


推荐阅读