Danny O
Danny O

Reputation: 17

Change dropdown lists dynamically

I have to make a small voting system for school.

I have 2 dropdown lists. You have 10 points to vote with. If the person selects 9 at the first dropdown list the second dropdownlist shows only the number 1. The other way around it does the same.

My code for this code:

        protected void ddLuuk_SelectedIndexChanged(object sender, EventArgs e)
    {

//dd means dropdownlist.

        ddGabriel.Items.Clear();
        var value = ddLuuk.SelectedValue;
        if (value == "10")
        {
            ddGabriel.Items.Add("0");
        }
        else if (value == "9")
        {
            ddGabriel.Items.Add("1");
        }
        else if (value == "8")
        {
            ddGabriel.Items.Add("1");
            ddGabriel.Items.Add("2");
        }

// etc etc.

Now my problem with this code: Let's say I have to increase the number to 100. We shouldn't make 100 of those else if constructions.

My question is: How can I make this code much more cleaner and make it work with 100 numbers?

Thanks in advance!

Upvotes: 0

Views: 1104

Answers (4)

Sebastian Siemens
Sebastian Siemens

Reputation: 2421

        ddGabriel.Items.Clear();
        var value = (int)ddLuuk.SelectedValue;
        if (value == 10)
        {
            Enumerable.Range(0, 1).ToList().ForEach(i => ddGabriel.Items.Add(i.ToString()));
        }
        else if (value < 10)
        {
            Enumerable.Range(1, 10 - value).ToList().ForEach(i => ddGabriel.Items.Add(i.ToString()));
        }

Upvotes: 0

usselite
usselite

Reputation: 816

How about:

    private int totalPoints = 100;
    protected void ddLuuk_SelectedIndexChanged(object sender, EventArgs e)
    {
        ddGabriel.Items.Clear();
        var value = ddLuuk.SelectedValue;

        int pointsToGive = totalPoints - Convert.ToInt32(value);

        for (int i = 0; i < pointsToGive ; i++)
        {
            ddGabriel.Items.Add(i.ToString());
        }
    }

Basically we are going to calculate the difference of the points you gave someone and the total points you can give someone. That difference is used to add in an loop new elements.

I guess usually though Javascript would be more fitting.

Upvotes: 1

BiggerD
BiggerD

Reputation: 303

Since this is probably homework, I'll help you by giving a clue: you will need a for loop

Upvotes: 0

Th0rndike
Th0rndike

Reputation: 3436

It's easy, all results are '10 - ValueOfDropDown'.

Generalizing, we could say that 10 is the maximum dropdown value. So, putting it in a variable i would become 'MaxValue - ValueOfDropDown'

The only thing you should be aware of is that you need to parse the dropdown value in order to make it a number, for this use 'int.Parse(value)'

Upvotes: 0

Related Questions