Search code examples
c#.netasp.netalgorithmstack-overflow

Stack Overflow error on Color Changer Function


i have two color "red" also "Salmon". i need create dynamiclly panel also panel background color. These colors must be between two color(red

 public Color x, y;
        protected void Page_Load(object sender, EventArgs e)
        {
            BackGroundColorArranger(Color.Red, Color.Salmon);
        }
        void BackGroundColorArranger(Color x, Color y)
        {

            BackGroundColorArrangerBase(Convert.ToInt32((float)(x.ToArgb() + y.ToArgb()) / 2));
        }
        void BackGroundColorArrangerBase(int z)
        {
            Panel panel = new Panel();
            panel.ID = z.ToString();
            panel.Width = 150;
            panel.Height = 50;
            panel.BackColor = Color.FromArgb(z);
            this.Controls.Add(panel);
            BackGroundColorArranger(x, Color.FromArgb(z));
        }

But how can i do this. Above codes give me stackoverflow error.


Solution

  • As they have said you have an infinite recursive loop, and that's why you're getting the Stack Overflow.

    As a quick fix remove this line from BackGroundColorArrangerBase:

    BackGroundColorArranger(x, Color.FromArgb(z));
    

    So it looks like this:

            void BackGroundColorArrangerBase(int z) 
            {
               Panel panel = new Panel();
               panel.ID = z.ToString(); //this wil generate the same id for the same pair of colors
               panel.Width = 150;
               panel.Height = 50;
               panel.BackColor = Color.FromArgb(z);
               this.Controls.Add(panel);
            }
    

    That should stop the recursion. Its not very clear what you need beyond the dynamic panel creation. As is the code will just create one panel, and will create a new panel every time the BackGroundColorArranger is called -WITH A DIFFERENT COLOR PAIR- as you are using the colorpair as an ID for the panel.

    If you need more than one panel make a finite loop calling BackGroundColorArranger with different pairs of colors ... if you need to actually see the panels on screen you'll need to change panel.Location of each in ArrangerBase, as now each panel starts at the origin with a fixed size.