Click here to Skip to main content
15,885,906 members
Please Sign up or sign in to vote.
2.00/5 (2 votes)
See more:
C#
Button[,] btn = new Button[Convert.ToInt32(textBox1.Text), Convert.ToInt32(textBox2.Text)];

           for (int i = 0; i < Convert.ToInt32(textBox1.Text); i++)
           {
               for (int j = 0; j <= Convert.ToInt32(textBox2.Text); j++)
               {
                   btn[i, j] = new Button();
                   this.Controls.Add(btn[i, j]);

                   if (i > 2)
                   {
                       btn[i, j].Left = 100 + btn[i-1, j-1].Left;
                       btn[i, j].Top = 100 + btn[i-1, j-1].Top;
                   }
                   else
                   {
                       btn[i, j].Left = 100;
                       btn[i, j].Top = 100;
                   }


               }

           }


it says index out of Range.
I dont know why!
Posted
Comments
[no name] 10-Jul-12 10:38am    
Because you are iterating over your array too many times.
Sergey Alexandrovich Kryukov 10-Jul-12 15:49pm    
What, if you didn't see the problem immediately, never used the debugger? Try to solve the simple problems on your own.
--SA

1 solution

Correct the loop for j:

C#
//for (int j = 0; j <= Convert.ToInt32(textBox2.Text); j++)
for (int j = 0; j < Convert.ToInt32(textBox2.Text); j++)


And this causes error too:
C#
if (i > 2)
{
    btn[i, j].Left = 100 + btn[i-1, j-1].Left;
    btn[i, j].Top = 100 + btn[i-1, j-1].Top;
}


Use this one instead:
C#
//if (i > 2)
//{
//    btn[i, j].Left = 100 + btn[i-1, j-1].Left;
//    btn[i, j].Top = 100 + btn[i-1, j-1].Top;
//}

btn[i, j].Left = (i > 0)? 100 + btn[i - 1, j].Left : 100;

btn[i, j].Top = (j > 0)? 100 + btn[i, j - 1].Top : 100;
 
Share this answer
 
v5
Comments
Sander Rossel 10-Jul-12 11:09am    
Simple, yet effective. My 5.
Shahin Khorshidnia 10-Jul-12 11:10am    
Thank you very much Naerling :)
Sergey Alexandrovich Kryukov 10-Jul-12 15:49pm    
Sure, a 5.
--SA
Shahin Khorshidnia 10-Jul-12 23:49pm    
Thank you a lot :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900