首页 > 解决方案 > 使用来自 datagridview 的信息以另一种形式更新计时器标签

问题描述

好的,我想我可以在再次检查所有内容后准确地问这个问题。我正在尝试以另一种形式更新计时器倒计时标签。表单 2 中的标签显示从数据网格视图中选择的单元格添加到表单 1 中的计时器。到目前为止,我可以增加和减少添加到 dgv 的时间量以及更新和删除行本身。我的问题是,虽然我可以在另一种形式的单元格中显示时间,但一旦表格 2 出现,我似乎无法让它倒计时。我设法确认表格 2 中的计时器正在工作,它只是我遇到问题的标签。到目前为止,这是我在表格 2 中尝试让它倒计时的方法,但似乎没有任何效果。如果我的技术词汇不足,我是编程新手,很抱歉。

public partial class Form1 : Form
{

    TimeSpan TotalTimeLeft;
    TimeSpan AdditionalTime;
    DateTime StartTime;
    DateTime WhenTimesUpTime;
    public int TotalHours;
    public int TotalMinutes;
    public int TotalSeconds;
    public int RemainingSeconds;
    public Form1()
    {
        InitializeComponent();
        timer1.Enabled = true;
        StartTime = DateTime.Now;
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }

    private void openToolStripMenuItem_Click(object sender, EventArgs e)
    {

    }

    private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
    {
        Form2 form2 = new Form2();
        form2.Show();
        form2.timer1.Start();
        form2.TimerDisplay2.Text = dataGridView1.CurrentCell.Value.ToString();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        // creat a variable to hold an int value to create new rows and connect it to the datagridview.
        //Adds a row
        int n = dataGridView1.Rows.Add();
        dataGridView1.Rows[n].Cells[0].Value = PasswordText.Text;
        dataGridView1.Rows[n].Cells[1].Value = TimerDisplay.Text;
        // clears textbox after data is entered
        PasswordText.Clear();
        //resets label text back to default
        TimerDisplay.Text = "" + String.Format("{0,2:d2}", TotalHours) + ":" + String.Format("{0,2:d2}", TotalMinutes) + ":" + String.Format("{0,2:d2}", RemainingSeconds);
        //Resets Time increase back to 0
        AdditionalTime = new TimeSpan();
    }

    private void button2_Click(object sender, EventArgs e)
    {
        //Removes a row
        foreach (DataGridViewRow row in dataGridView1.SelectedRows)
            if (!row.IsNewRow) dataGridView1.Rows.Remove(row);

    }

    private void button3_Click(object sender, EventArgs e)
    {
        //Updates info
        DataGridViewRow newDataRow = dataGridView1.SelectedRows[0];
        newDataRow.Cells[0].Value = PasswordText.Text;
        newDataRow.Cells[1].Value = TimerDisplay.Text;
    }

    private void button4_Click(object sender, EventArgs e)
    {
        //Increases time by set amount
        // Add time button
        AddTimeMinutes(5);
        
        
    }
    private void AddTimeMinutes(int MinutesToAdd)
    {
        AdditionalTime = AdditionalTime.Add(TimeSpan.FromMinutes(MinutesToAdd));
        //Tio: Substract the current time from when the time will be up as a timespan
        
        // Calculate total hours

        TotalHours = (int)AdditionalTime.TotalHours;

        //Tio: Calculate Total minutes and save to an integer.

         //int TotalMinutes = (int)AdditionalTime.TotalMinutes;
        TotalMinutes = (int)AdditionalTime.Minutes;

        //Tio: Calculate remaining seconds after the total minutes to display along with the minutes remaining.

        //TotalSeconds = (int)AdditionalTime.Seconds;

        int RemainingSeconds = (int)AdditionalTime.TotalSeconds - ((int)TotalMinutes * 60) - ((int)TotalHours * 3600);

        //Tio: Display the time left in minutes and seconds.
        //MessageBox.Show("Total Hours:" + TotalHours.ToString() + " Total Minutes:" + TotalMinutes.ToString() + " Total Seconds:" + TotalSeconds.ToString());

        TimerDisplay.Text = "" + String.Format("{0,2:d2}", TotalHours) + ":" + String.Format("{0,2:d2}", TotalMinutes) + ":" + String.Format("{0,2:d2}", RemainingSeconds);

        
     
    }

    private void button5_Click(object sender, EventArgs e)
    {
        // Decrease time button
        AddTimeMinutes(-5);
    }
}

 public partial class Form2 : Form
{
    TimeSpan TotalTimeLeft;
    TimeSpan AdditionalTime;
    DateTime StartTime;
    DateTime WhenTimesUpTime;
    public int TotalHours;
    public int TotalMinutes;
    public int TotalSeconds;
    public int RemainingSeconds;
    public Form2()
    {
        InitializeComponent();
        timer1.Enabled = true;
        timer1.Start();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Close();
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        if (TotalHours > 0)
        {
            // Display the new time left
            // by updating the Time Left label.
            TotalHours = TotalHours - 1;
            TimerDisplay2.Text = TotalHours + "" + String.Format("{0,2:d2}", TotalHours);
        }
        else if (TotalMinutes > 0)
        {
            // If the user ran out of time, stop the timer, show
            // a MessageBox, and fill in the answers.
            TotalMinutes = TotalMinutes - 1;
            TimerDisplay2.Text = TotalMinutes + ":" + String.Format("{0,2:d2}", TotalMinutes);
        }
        else if (RemainingSeconds > 0)
        {
            RemainingSeconds = RemainingSeconds - 1;
            TimerDisplay2.Text = RemainingSeconds + ":" + String.Format("{0,2:d2}", RemainingSeconds);
        }

        else
        {
            timer1.Stop();
        }
    }
    public void AddTimeMinutes(int MinutesToAdd)
    {
        AdditionalTime = AdditionalTime.Add(TimeSpan.FromMinutes(MinutesToAdd));
        //Tio: Substract the current time from when the time will be up as a timespan

        // Calculate total hours

        TotalHours = (int)AdditionalTime.TotalHours;

        //Tio: Calculate Total minutes and save to an integer.

        //int TotalMinutes = (int)AdditionalTime.TotalMinutes;
        TotalMinutes = (int)AdditionalTime.Minutes;

        //Tio: Calculate remaining seconds after the total minutes to display along with the minutes remaining.

        //TotalSeconds = (int)AdditionalTime.Seconds;

        int RemainingSeconds = (int)AdditionalTime.TotalSeconds - ((int)TotalMinutes * 60) - ((int)TotalHours * 3600);

        //Tio: Display the time left in minutes and seconds.
        //MessageBox.Show("Total Hours:" + TotalHours.ToString() + " Total Minutes:" + TotalMinutes.ToString() + " Total Seconds:" + TotalSeconds.ToString());

        TimerDisplay2.Text = "" + String.Format("{0,2:d2}", TotalHours) + ":" + String.Format("{0,2:d2}", TotalMinutes) + ":" + String.Format("{0,2:d2}", RemainingSeconds);



    }
}

标签: c#datagridviewtimerlabel

解决方案


我会尽我所能使这个简单。您的问题有两 (2) 个问题……即倒数计时器不工作,另一个表格上的标签没有更新。尽管倒计时是标签显示在其他表单上的内容,但您拥有的当前代码无法更新此标签。

对于另一种形式的标签,一个简单的解决方案是Form2通过其构造函数“传递”该标签。喜欢:

Form2 f2 = new Form2(lblForm1CountDown);

然后在 中Form2,创建一个Label parentCDLabel然后把这个标签赋值给Label构造函数中传入的。像……</p>

Label parentCDLabel;

public Form2(Label pCDLabel) {
  InitializeComponent();
  parentCDLabel = pCDLabel;
   …..
}

现在,Form2可以访问Form1' 标签,我们可以在更新标签时更新它Form2

这可以解决 1 个问题。

接下来是倒计时。有很多方法可以做到这一点,但是,“手动”管理倒计时小时、分钟和秒是错误的方法。当然可以,但是有更简单、更可靠的方法来实现这种“倒计时”。</p>

要点是在处理“时间”值时,请使用“时间”类型的对象,例如TimeSpan. 您当前的代码使用多个TimeSpan对象,这不仅使事情复杂化,而且没有必要。Timer您可以使用一 (1)个对象和一个对象进行计时器倒计时显示TimeSpan

我将从form1 CellDoubleClick事件中假设这是您将“总时间”倒计时的地方。我一直不清楚。但是,这很重要。如果我们想倒数到零……我们从什么时间跨度值开始?在当前发布的代码中,我猜这个开始倒计时的“总时间”来自用户“双击”的单元格。

这里的重点是,“无论如何”这个起始“总时间”是被获取的……form2从来没有给出这个重要的起始信息。例如,假设用户双击了一个单元格,其中TimeSpan... TimeSpan(0, 1, 15)1 分 15 秒的跨度。这就是我们想要开始倒计时的内容。Form2需要知道这一点才能知道从哪里开始倒计时。当前代码没有将这个重要信息传递给form2它,它应该传递给它。

鉴于此,看来我们需要将另一个参数传递给From2. 这将是一个TimeSpan对象,表示我们想要开始倒计时的时间跨度值。form1下面是将这个值传递给的示例form2。由于不清楚代码如何获取此值,我只是提供了一个新TimeSpan对象。传递 1 分 30 秒的起始值可能看起来像……</p>

Form2 f2 = new Form2(new TimeSpan(0, 1, 30), lblForm1CountDown);

然后在Form2 创建一个TimeSpan对象并将其分配给传入的TimeSpan对象......。

TimeSpan totalTime;

public Form2(TimeSpan tTime, Label pCDLabel) {
  InitializeComponent();
  totalTime = tTime;
  parentCDLabel = pCDLabel;
}

现在Form2拥有启动倒数计时器所需的所有信息。它有一个起始倒计时值,并且当倒计时发生变化时,它有要更新的 form1 的标签。为了提供帮助,form2将使用Timer每秒触发一次的 a。当它触发时,想法是从起始值中减去 1 秒TimeSpan,更新标签,就是这样。检查小时、分钟和秒是不必要的。我们每秒继续此操作,直到TimeSpan值达到零 (0)。此时,时间已经不多了。

将所有这些放在一起......Form1将获得起始值TimeSpan和标签并将它们传递给form2如上所示。在Form2一个Timer被创建为每秒触发一次。此外,TimeSpan使用了两个对象。totalTime是传入的开始时间跨度,timeLeft用于显示剩余时间。这里没有必要使用两个变量,totalTime只是用来让用户随时知道他们开始了多少时间。该timeLeft变量显然会每秒“更新”一次。当表单初始化时……我们连接计时器滴答事件并设置 1 秒的间隔,然后在加载时启动计时器。

TimeSpan totalTime;
TimeSpan timeLeft;
Timer timer1 = new Timer();
Label parentCDLabel;
StringBuilder sb;

public Form2(TimeSpan tTime, Label pCDLabel) {
  InitializeComponent();
  timeLeft = tTime;
  totalTime = tTime;
  parentCDLabel = pCDLabel;
  timer1.Tick += timer1_Tick;
  timer1.Interval = 1000;
}

private void Form2_Load(object sender, EventArgs e) {
  timer1.Start();
}

最后,timer1_Tick事件。触发时,我们只需从timeLeft更新两个表单上的标签中减去一 (1) 秒,然后最后检查时间是否已用完。

private void timer1_Tick(object sender, EventArgs e) {
  timeLeft = timeLeft.Subtract(new TimeSpan(0, 0, 1));
  sb = new StringBuilder();
  sb.AppendLine("Total time: " + totalTime.Hours + ":" + totalTime.Minutes + ":" + totalTime.Seconds);
  sb.AppendLine(" Time left: " + timeLeft.Hours + ":" + timeLeft.Minutes + ":" + timeLeft.Seconds);
  lblCountDown.Text = sb.ToString();
  parentCDLabel.Text = sb.ToString();
  if (timeLeft.Ticks <= 0) {
    timer1.Stop();
    MessageBox.Show("Time has run out!");
  }
}

我希望这是有道理的并有所帮助。


推荐阅读