Generate sequencial number based on two Date using C# and VB.Net

Last Reply 5 months ago By kalpesh

Posted 5 months ago

How to add number and dates to table like this

I wand datatable looks like this

1 01-02-2018
1 02-02-2018
1 03-02-2018
2 01-02-2018
2 02-02-2018
2 03-02-2018
3 01-02-2018
3 02-02-2018
3 03-02-2018

I can add date sequence from 1st feb to 3rd feb

but I want add date sequence for each number between 1 to 3

   Dim date1 As Date
   Dim date2 As Date
   dt.Columns.Add("SId")
   dt.Columns.Add("RDate")
   date1 =  "01-02-2018"
   date2 = "03-02-2018"
   If date1 = date2 Then
 
   ElseIf date1 > date2 Then
       MsgBox("Please Enter a Valid Date Range")
   Else
       dt.Rows.Add(date1)
       Do Until date1 = date2
           date1 = date1.AddDays(1)
           dt.Rows.Add(date1)
       Loop
       Date.Parse(date2)))
   End If

 

Posted 5 months ago

1) You need to pass the both date in proper format so you can compare it as it takes is in MM-dd-YYYY format.

Check the below sample code and implement it as per your code logic in your code.

C#

DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[2] { new DataColumn("SId",typeof(int))
                                    ,new DataColumn("RDate",typeof(string))});

DateTime date1 = Convert.ToDateTime("02-01-2018");
DateTime date2 = Convert.ToDateTime("02-03-2018");
if (date1 > date2)
{ 
    //MessageBox("Please Enter a Valid Date Range");
}
else
{
    int datediff = date2.Subtract(date1).Days + 1;
    for (int i = 1; i <= datediff; i++)
    {
        for (int j = 0; j < datediff; j++)
        {
            dt.Rows.Add(i, date1.AddDays(j));
        }
    }
}

VB.Net

Dim dt As DataTable = New DataTable()
dt.Columns.AddRange(New DataColumn(1) {New DataColumn("SId", GetType(Integer)), New DataColumn("RDate", GetType(String))})
Dim date1 As Date = Convert.ToDateTime("02-01-2018")
Dim date2 As Date = Convert.ToDateTime("02-03-2018")
If date1 > date2 Then
    ' Your Message box code
    ' MsgBox("Please Enter a Valid Date Range")
Else
    Dim datediff As Integer = date2.Subtract(date1).Days + 1
    For i As Integer = 1 To datediff
        For j As Integer = 0 To datediff - 1
            dt.Rows.Add(i, date1.AddDays(j))
        Next
    Next
End If