How to Bind Year and months to Dataset ?

Posted by Nandkishorre under C# on 5/18/2013 | Points: 10 | Views : 1273 | Status : [Member] | Replies : 2
Hi,
I need to bind data to datset as Years and Months in Below foramt from current month and year through C# code or Sql Server Fucntion or Procedure.
if any one know colud you tell me the answer.
Year Month
2013 May
2013 June
2013 July
2013 August
2013 September
2013 October
2013 November
2013 December
2014 January
2014 February
2014 March
2014 April

Regards
Nanda Kishore.CH




Responses

Posted by: Niladri.Biswas on: 5/18/2013 [Member] Platinum | Points: 25

Up
0
Down
C#

using System;

using System.Data;
using System.Globalization;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int monthsToGenerate = 12;
DataTable dt = new DataTable();
dt.Columns.Add("Year",typeof(int));
dt.Columns.Add("Month",typeof(string));

for (int i = 0; i < monthsToGenerate; i++)
{
var date = DateTime.Now.AddMonths(i);

var year = date.Year;
var monthName = date.ToString("MMMM", CultureInfo.InvariantCulture);

dt.Rows.Add(year, monthName);
}
}
}
}


Best Regards,
Niladri Biswas

Nandkishorre, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Niladri.Biswas on: 5/18/2013 [Member] Platinum | Points: 25

Up
0
Down
SQL SERVER

DECLARE @monthsToGenerate INT = 12

DECLARE @startDate DATE=CAST(MONTH(GETDATE()) AS VARCHAR) + '/' + '01/' + + CAST(YEAR(GETDATE()) AS VARCHAR) -- mm/dd/yyyy
DECLARE @endDate DATE=DATEADD(mm, @monthsToGenerate-1, @startDate)

SELECT
[Date] = DATEADD(mm,Number,@startDate) ,
[Year] = DATEPART(YEAR,DATEADD(mm,Number,@startDate))
,[Month] = DATENAME(MONTH,DATEADD(mm,Number,@startDate))
FROM master..spt_values
WHERE Type='P'
AND DATEADD(mm,Number,@startDate) <= @endDate


Best Regards,
Niladri Biswas

Nandkishorre, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response