Search code examples
c#asp.netwebformsdropdownbox

Getting DropDownList values


I have a problem with taking the values from a DropDownList. I understand how to put in a value and get that value out with using numbers but my problem I must a value such as FrBrb and then take that value in the code and set it to a value of 40 in my code. Here is what I have so far:

<asp:DropDownList ID="ddlRiverTour" runat="server">
                  <asp:ListItem Value="FrBrd">French Broad</asp:ListItem>
                  <asp:ListItem Value="Nant">Tuck</asp:ListItem>
                  <asp:ListItem Value="Tuck">Nantahala</asp:ListItem>
              </asp:DropDownList>

This is my DropDownList with the letter values in it. I have to use the value as these but can't use number values which would be very simple. The actual code to get these values and then use them in my calculations is the puzzling part. I don't know if I should define them then use an if statement to decide which is which and then do my calculations but how do I define them or is there an easier way? Here is the rest of my code so far:

riverTour = Convert.ToDecimal(ddlRiverTour.SelectedValue);
baseTourFee = rafters * riverTour;

I know this code doesn't work here but I did have an if statement that looked like this:

if (rivertour = FrBrd)
{
  baseTourFee = rafters * 40;
}

But that seems like a lot more code than is needed and doesn't work very smoothly.


Solution

  • Without having some way of giving each of the "words" in your list of <asp:ListItem> elements a specific numerical value, you're asking the compiler to do an impossible task.

    If you don't already have a way to specifically give them values, my suggestion would be to use an enum such as...

    public enum RiverTourEnum
    {
      FrBrd = 40,
      Nant = 50,
      Tuck = 60,
    }
    

    Then you can parse the value in the dropdown to the appropriate enum value and use the number that way...

     string ddVal = ddlRiverTour.SelectedValue;
     RiverTourEnum enumVal = (RiverTourEnum)Enum.Parse(typeof(RiverTourEnum), ddVal);
     int riverTourVal = (int)enumVal;
    

    This obviously makes the assumption that the "words" in the list have static values. If not, then you need to look at a different way to "lookup" exactly what numeric value should be used at that particular time


    After reading the question again (and comments under it), if you really want to use if statements, then you're probably after something like this...

    string riverTour = ddlRiverTour.SelectedValue;
    if (riverTour == "FrBrd")
    {
      baseTourFee = rafters * 40;
    }
    else if (riverTour == "Nant")
    ...
    

    Or a better approach would be...

    switch(ddlRiverTour.SelectedValue)
    {
      case "FrBrd" : 
        baseTourFee = rafters * 40;
        break;
      case "Nant" :
        ...
    }