mark333...333...333
mark333...333...333

Reputation: 1360

C# Wrong Loop On My DataGridView

Good day, I'm having an error. I choose the August 5, 2015 on the date picker with the loop count of 3. But I'm having a problem. I'm using add 15 prior to the given output. But the first count is wrong.

THE OUTPUT IN THE FIRST COUNT IS

8/20/2015
but it should be 
8/05/2015 because I use the 8/05/2015 on the datepicker.

I don't know what's the problem here.

Here's my code (This will be execute when the button "Calculate Schedule" is click"

private void execute_Click(object sender, EventArgs e)
{
   var fromDate = date_from.Value; // Getting the value from DatePicker

   int count;

   for (count = 0; count < 3; count++) {
      dgv_result.Rows.Add(1);
            int numrows = count + 1;

            fromDate = fromDate.AddDays(15); 

            dgv_result.Rows[count].Cells[1].Value = numrows; // Just for numbering the rows
            dgv_result.Rows[count].Cells[0].Value = fromDate.ToShortDateString();
   }
}

Here's my Screenshot

NOTE: Just check the Month only

Upvotes: 0

Views: 51

Answers (2)

Burk
Burk

Reputation: 3067

You are adding days before you write your first row. So you need to .AddDays(15) at the end line of for loop.

Upvotes: 1

Shaharyar
Shaharyar

Reputation: 12439

You just have to put this line at the end of the loop:

for (count = 0; count < 3; count++) 
{
    dgv_result.Rows.Add(1);
    int numrows = count + 1;

    dgv_result.Rows[count].Cells[1].Value = numrows; // Just for numbering the rows
    dgv_result.Rows[count].Cells[0].Value = fromDate.ToShortDateString();

    //add days after adding the row, so next line will be effected by it
    fromDate = fromDate.AddDays(15); 
}

I am considering you're not using fromDate anywhere else and it is just for the loop.

Upvotes: 3

Related Questions