s.milziadi
s.milziadi

Reputation: 705

Vb.Net How to create Months/Years dropdown lists

Which is the best way to create two dropdown lists one with months (maybe month names) and the other one with years?

They should return two values with this format: 1 (or 2, 3 etc.) for months and 2014 (or 2013, 2012 etc.) for years

Any suggestions?

Upvotes: 2

Views: 8967

Answers (4)

Karthikeyan P
Karthikeyan P

Reputation: 1267

Other way we can able to do like this,

VB Listbox,

Dim months = System.Globalization.DateTimeFormatInfo.InvariantInfo.MonthNames
For Each month As String In months
    If Not String.IsNullOrEmpty(month) Then
        ListBox1.Items.Add(month)
    End If
Next

Or Else

ListBox1.DataSource = System.Globalization.DateTimeFormatInfo.InvariantInfo.MonthNames

VB Combobox,

Dim months = System.Globalization.DateTimeFormatInfo.InvariantInfo.MonthNames
For Each month As String In months
    If Not String.IsNullOrEmpty(month) Then
        ComboBox1.Items.Add(month)
    End If
Next

Or Else

ComboBox1.DataSource = System.Globalization.DateTimeFormatInfo.InvariantInfo.MonthNames

Upvotes: 1

Ibrashcka
Ibrashcka

Reputation: 1

If you wish to have the current year with the previous years,this is the simplest answer :)

 int curYear = DateTime.Now.Year;

        for (int i = curYear; i >= 2006; i--)
        {
            ddYear.Items.Add(i.ToString());

        }

Upvotes: 0

rajesh
rajesh

Reputation: 115

protected void Page_Load(object sender, EventArgs e)
{

DropDownList ddltmp = new DropDownList();
int curYear = DateTime.Now.Year;

for(int i = 1; i < 76; ++i)
{

ListItem tmp = new ListItem();
tmp.Value = curYear.ToString();

tmp.Text = curYear.ToString();

ddltmp.Items.Add(tmp);

curYear = DateTime.Now.AddYears(i).Year;
}

this.form1.Controls.Add(ddltmp);
}

Upvotes: 0

शेखर
शेखर

Reputation: 17614

Looping will be the best for your solution. Create a for loop for year as follow

 for(int i=2000;i<2020;i++)
 {
      ddYear.Items.Add(new ListItem(i.ToString(), i.ToString());
 }

and for month

 DateTime month = Convert.ToDateTime("1/1/2000");
 for (int i = 0; i < 12; i++)
 {
      DateTime NextMont = month.AddMonths(i);
      ListItem list = new ListItem();
      list.Text = NextMont.ToString("MMMM");
      list.Value = NextMont.Month.ToString();
      MyddlMonthList.Items.Add(list);
 }

In VB

Dim month As DateTime = Convert.ToDateTime("1/1/2000")
  For i As Integer = 0 To 11
    Dim NextMont As DateTime = month.AddMonths(i)
    Dim list As New ListItem()
    list.Text = NextMont.ToString("MMMM")
    list.Value = NextMont.Month.ToString()
    MyddlMonthList.Items.Add(list)
  Next

Upvotes: 4

Related Questions