Reputation: 530
I have a date field that I populate a dropdownlist with. The date field is like this 2012-05-01 00:00:00
and I need the dropdown list to look like this 5/2012
. But to put a wrench in things, I need to pull the date apart before I put it back together again.
Specifically, I need to find all "distinct" months and all "distinct" years, but I only want to find the distinct year, if there is a datefield with a month for that year and vice-versa.
So I have the following data
Table: budget
id Item ItemDate
1 A 5/12/2012
2 B 5/14/2012
3 C 4/5/2012
4 D 4/7/2012
5 E 7/15/2011
So I want my dropdown list to show the following only:
5/2012
4/2012
7/2011
I have tried using
SELECT DISTINCT datepart(Month, ItemDate) + ' ' + datepart(year, ItemDate) As ddlList
FROM Budget
but that adds the month to the year (5 + 2012 = 2017).
and then my asp
<asp:dropdownlist id="ddl1" runat="server" datasourceID="sqldatasrc" DataTextField="ddlList"></dropdownlist>
Any ideas? I'm not sure I'm going about this the right way.
Upvotes: 1
Views: 1672
Reputation:
If I remember correctly, I believe you can use the property DataTextFormatString
available on the DropDownList control to format the boundfield values. You have to set the property to the value {0:M/yyyy}
. Please make sure that the property is available. I couldn't find it in MSDN.
I could find only ListControl.DataTextFormatString Property
You have to cast the MONTH
and YEAR
parts of the datetime field values to VARCHAR
or string data type before concatenating those values.
Click here to view the demo in SQL Fiddle.
SELECT
DISTINCT CAST(DATEPART(MONTH, ItemDate) AS VARCHAR) + '/' +
CAST(DATEPART(YEAR, ItemDate) AS VARCHAR) AS ddlList
FROM dbo.Budget
SELECT
DISTINCT CAST(MONTH(ItemDate) AS VARCHAR) + '/' +
CAST(YEAR(ItemDate) AS VARCHAR) AS ddlList
FROM dbo.Budget;
CREATE TABLE dbo.Budget
(
Id INT NOT NULL
, Item VARCHAR(10) NOT NULL
, ItemDate DATETIME NOT NULL
)
INSERT INTO dbo.Budget (Id, Item, ItemDate) VALUES
(1, 'A', '05/12/2012'),
(2, 'B', '05/14/2012'),
(3, 'C', '04/05/2012'),
(4, 'D', '04/07/2012'),
(5, 'E', '07/15/2012');
DDLLIST
-------
4/2012
5/2012
7/2012
Upvotes: 4