Search code examples
c#winformsfor-loopdatagridviewtimespan

C# Incrementing Interval


I'm trying to achieve an interval the increments with each step. If the initial interval is 30 and the increment level is 1: the next interval is 31, then 32, 33...

int ii = 1800
int ib = 60

private void generateGridBtn_Click(object sender, EventArgs e)
{
    dataGridView1.Rows.Clear();

    for (int i = 0; i < 1000; i++)
    {
        TimeSpan iiTS = TimeSpan.FromSeconds(ii);
        DateTime nextDT = DateTime.Now.Add(iiTS);
        dataGridView1.Rows.Add();
        dataGridView1.Rows[i].Cells[0].Value = nextDT.ToString("dd.MM.yyyy HH:mm:ss");
        ii = ii + ib;
    }
}

This is a for loop that starts with two integers, one for the interval, and one for the increment, but it doesn't produce the desired results. It only adds one number. There is no increase.


Solution

  • It looks like you wanted to make the next:

    private void generateGridBtn_Click(object sender, EventArgs e)
    {
        dataGridView1.Rows.Clear();
        DateTime nextDT = DateTime.Now;
        for (int i = 0; i < 1000; i++)
        {
            TimeSpan iiTS = TimeSpan.FromSeconds(ii);
            nextDT = nextDT.Add(iiTS);
            dataGridView1.Rows.Add();
            dataGridView1.Rows[i].Cells[0].Value = nextDT.ToString("dd.MM.yyyy HH:mm:ss");
            ii = ii + ib;
        }
    }
    

    nextDT is the timestamp to increase on each cycle step.

    To optimize:

    private void generateGridBtn_Click(object sender, EventArgs e)
    {
        dataGridView1.Rows.Clear();
        DateTime nextDT = DateTime.Now;
        int lim = ii + 1000 * ib;
        for (int i = ii; i < lim; i += ib)
        {
            nextDT = nextDT.AddSeconds(i);
            dataGridView1.Rows.Add();
            dataGridView1.Rows[i].Cells[0].Value = nextDT.ToString("dd.MM.yyyy HH:mm:ss");
        }
    }