1

I'm trying to learn recursion in C#. I am able to do a simple count down in a console application, but I am not sure how to do the same thing in an ASP.NET web application. I would like to display the result in a listbox, but I cannot access the listbox in a static function.

Here is what I have for my console application:

    static void Main(string[] args)
    {
        int startInt = 100;
        countDown(startInt);
        Console.ReadLine();

    }
    public static void countDown(int integer)
    {
        if (integer == 1)
        {
            Console.WriteLine(integer);
        }
        else 
        {
            Console.WriteLine(integer);
            integer--;
            countDown(integer);
        }
    }   

Any help on getting this to work in a web application that will display the numbers in a listbox?

2
  • Pass the listbox as additional parameter. Commented Apr 20, 2013 at 22:11
  • Take a look at my answer to a previous question which gives an example of using recursion in a C# ASP.NET application stackoverflow.com/a/9753547/459517 Commented Apr 21, 2013 at 20:16

2 Answers 2

1

You shouldn't need to keep it static, since you're no longer calling it from a static function. Using a countDown function like this one

public void countDown(int integer)
{
    if (integer > 0)
    {
        ListBox1.Items.Add(integer.ToString());
        integer--;
        countDown(integer);
    }
} 

should work just fine. I tested it out by putting

int startInt = 100;
countDown(startInt);

in the Page_Load method, and the ListBox displays as expected.

Sign up to request clarification or add additional context in comments.

2 Comments

The problem is about accessing objects from a static method. So your answer is not suitable, I guess.
What an unfortunate duplication of code. It should really be rewritten.
0

I am not sure if there are performance issues, or better solutions. But this works and could be a good example for undrstanding recursion.

protected void Page_Load(object sender, EventArgs e)
{
    int startInt = 100;
    form1.Controls.Add(countDown(startInt, new ListBox()));
}

public static ListBox countDown(int integer, ListBox lb)
{
    ListItem li = new ListItem();

    if (integer > 0)
    {
        li.Text = integer.ToString();
        lb.Items.Add(li);

        integer--;
        countDown(integer, lb);
    }
    return lb;

}   

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.