Results 1 to 2 of 2

Thread: csharp for looping

  1. #1

    Thread Starter
    Fanatic Member merhaba's Avatar
    Join Date
    Sep 2002
    Location
    Istanbul,Bartin-Gallipoli(Gelibolu-Canakkale)
    Posts
    601

    csharp for looping

    I am tring to assign random numbers to each 4 label .on my form.but I got stuck.. would you pls fix it ?


    PHP Code:

    private void timer1_Tick(object senderEventArgs e)
            {
                
    Random RandomClass = new Random();
                
                 for (
    int a 1<= 4a++)
                 {
                   
    int rn(a) = RandomClass.Next(120);  
                     
    lb(a).Left lb(a).Left rn;
                 }
            } 


    Thanks

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: csharp for looping

    Maybe it would be a good idea if you were to explain exactly what you're trying to achieve with your code rather than just posting the code and asking us to fix it. If we don't know what exactly it's supposed to do then how can we make it do it? Please consider this when posting in future.

    First of all, you wouldn't create a new Random object each time. You should create one Random object and assign it to a member variable, then use it every time.

    Now, can I confirm exactly what you're trying to do there? It looks like you're trying to move each Label in the horizontal direction, where the amount you move it is a random value from 1 to 20. Is that correct? If so it should look like this:
    Code:
    private Random rnd = new Random();
    
    private void timer1_Tick(object sender, EventArgs e)
    {
        foreach (Label lbl in this.labels)
        {
            lbl.Left += rnd.Next(1, 21);
        }
    }
    Note that that will keep moving the Labels to the right, so before long they're going to disappear off the right edge of the form.

    Note also that the maximum value returned by the Next method is always less than the value you specify, so if you want 20 to be a possible result then you have to specify 21 as the maximum.
    Last edited by jmcilhinney; Sep 8th, 2007 at 08:12 PM.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width