0

I have a DropDownList for year selection and I filled it with following default values.

Instead of which, is there any option to fill it using for-loop like I have given in below code as comment.

var yr = new List<Object>
{ 
    new { value=0 ,text="--Select--"},
    new { value = 2015 , text = "2015" },
    new { value = 2016 , text = "2016" },
    new { value = 2017 , text = "2017" },
    new { value = 2018 , text = "2018" },
    new { value = 2019 , text = "2019" },
    new { value = 2020 , text = "2020" },
    //new { for(int i = 2010;i <= DateTime.Now.Year+5; i++) value = i , text = i },
};
ViewBag.Year = new SelectList(yr, "value", "text");    
5
  • List<T> has an "Add" method... Commented Mar 15, 2016 at 11:31
  • Yes - that has an Add method as well. (List<Object> is a List<T>...) Commented Mar 15, 2016 at 11:34
  • 1
    You can use the loop, but create a SelectListItem not object and just assign that to ViewBag.Year - there is no need to the SelectList constructor. And add the labelOption in the DropDownListFor() method, not in the controller. Commented Mar 15, 2016 at 11:38
  • 1
    And you can simplify it even further using the Enumerable.Range() method Commented Mar 15, 2016 at 11:41
  • 1
    ViewBag.Year = Enumerable.Range(2010, DateTime.Now.Year + 5 - 2010).Select(x => new SelectListItem { Value = x.ToString(), Text = x.ToString() }); Commented Mar 15, 2016 at 11:50

3 Answers 3

1

You could initialize your List with value 0 by using collection initializer and then use for loop like this:

var yr = new List<Object> {new {value = 0, text = "--Select--"}};
for (var i = 2015; i <= 2020; i++)
{
    yr.Add(new { value = i, text = i.ToString() });
}
Sign up to request clarification or add additional context in comments.

Comments

0

Will this work for you ?

List<object> l = new List<object>();
for (int i = 2015; i < 2020; i++ )
    l.Add(new { value = i, text = i });

Comments

0

Yes, you can use method Add of List.

i.e.

for (int i = 2015; i < DateTime.Now.Year+5; i++ )
{
    yr.Add(new { value = i, text = i });
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.