POPULATE DROPDOWNLIST WITH ALL NUMBERS IN BETWEEN 2 NUMBERS

Hugh Jackman

Total Post:51

Points:359
Posted by  Hugh Jackman
C#  Dropdown 
 891  View(s)
Ratings:
Rate this:
<asp:DropDownList ID="ddlAge" runat="server"/> 
Label ages = (Label)e.Row.FindControl("Ages"); 
//The value ages returns is different every time but it will be in this format
// 3 - 11

So i would like to grab the 3 from the left of the dash and then grab the 11 from the right of the dash and populate my dropdownlist with the values of 3,4,5,6,7,8,9,10,11 if possible just not sure how to go about doing this.

  1. jacob rasel

    Post:88

    Points:616
    Re: populate dropdownlist with all numbers in between 2 numbers

    You can do this: 

    private IEnumerable<int> GetAgesBetween(string agesText) {
        var parts =agesText.Split('-');
        var start =int.Parse(parts[0].Trim());
        var end =int.Parse(parts[1].Trim());
        return Enumerable.Range(start, 1 + end-start);
    }

    You can use that method to retrieve the numbers and use them to populate the drop down list. 

    Hope it helps

      Modified On Apr-07-2018 04:35:49 AM
  1. Mark Devid

    Post:102

    Points:714
    Re: populate dropdownlist with all numbers in between 2 numbers

    This is in VB, but you can convert it in C#. This is just so that you get an idea as to how you can approach this problem. Here is the code:

     

         Dim ageData() As String = ages.split("-".ToCharArray())
     
         If ageData.Count = 2 AndAlso IsNumeric(ageData(0).Trim) AndAlso IsNumeric(ageData(1).Trim) Then
            For i As Integer = CInt(ageData(0)) To CInt(ageData(1).Trim) Step +1
               ddlAge.Items.Add(i)
            Next
         End If

     

      Modified On Apr-07-2018 04:35:11 AM

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!