如何使用计时器逐个显示和循环记录从数据库到标签

时间:2017-07-09 03:01:35

标签: c# windows

我正在使用C#开发Windows窗体项目,其中我需要显示从访问数据库到标签的记录,但它不应该一次显示整个记录,而应该一次显示来自数据库的记录,依此类推循环一个一个有计时器说5秒。任何建议都会有所帮助,并且会非常值得一提。 下面是我尝试但放弃的代码:

   private void BindLabel()
   {
        string constring = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\LicensedDB.accdb;
        Persist Security Info=True;Jet OLEDB:Database Password=abc123";
        using (OleDbConnection con = new OleDbConnection(constring))
        {
            using (OleDbCommand cmd = new OleDbCommand("SELECT TaskDetails FROM TaskReminder ", con))
            {
                cmd.CommandType = CommandType.Text;
                using (OleDbDataAdapter sda = new OleDbDataAdapter(cmd))
                {
                    using (DataTable dt = new DataTable())
                    {
                        sda.Fill(dt);

                       //label1
                        // Please guide me, any suggestion will be higly helpful and appreciable.

                    }
                }
            }
        }
    }

1 个答案:

答案 0 :(得分:1)

使DataTable全局化,然后使用计时器

DataTable dtReminders = null;
int i = 0;
private void BindLabel()
   {
        string constring = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\LicensedDB.accdb;
        Persist Security Info=True;Jet OLEDB:Database Password=abc123";
        using (OleDbConnection con = new OleDbConnection(constring))
        {
            using (OleDbCommand cmd = new OleDbCommand("SELECT TaskDetails FROM TaskReminder ", con))
            {
                cmd.CommandType = CommandType.Text;
                using (OleDbDataAdapter sda = new OleDbDataAdapter(cmd))
                {
                        sda.Fill(dtReminders);    
                        if(dtReminders.Rows.Count > 0)
                          timer.Start();
                }
            }
        }
    }

在计时器刻度事件中添加以下行

if(i >= dtReminders.Rows.Count)
    i = 0;
if(dtReminders.Rows[i]["columnName"] != null)
     lblRemider.Text = dtReminders.Rows[i]["columnName"].ToString();
     i++;