Page 1 of 1

Add Control to a Random() location on form.

Posted: Wed Aug 22, 2012 4:14 pm
by Scottie1972
ok guys I need help again. im thinking someone knows how todo this properly.
Image

ok what i need is this.
i need to be able to add an undetermend number of a "UserControl" to a vb form at random locations.
plus not to have any other control overlapping another control.

Basic UserControl layout is a background image and maybe 2 labels and that is it.
i just need to add the random() function to add the usercontrol to the form in the correct way.

at the moment i am using this code but it does not work like i need it to.
Code: Select all
    Dim RandomClass As New Random()

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        Dim ax As Integer = 10
        For i = 1 To ax
            Dim pb As New PictureBox
            pb.SizeMode = PictureBoxSizeMode.AutoSize
            pb.Image = Image.FromFile(Application.StartupPath + "\images\buildings\base.png")
            pb.BackColor = Color.Transparent
            pb.Location = New Point(RandomClass.Next(Me.Width), RandomClass.Next(Me.Height))
            

            Me.Controls.Add(pb)
        Next


    End Sub

Re: Add Control to a Random() location on form.

Posted: Wed Aug 22, 2012 6:22 pm
by M1z23R
I made this, i think you can edit it to your needs...

Re: Add Control to a Random() location on form.

Posted: Wed Aug 22, 2012 6:40 pm
by CodenStuff
#M1z23R is a good solution and I also had a bash at it using math code:
Code: Select all
    Dim RandomClass As New Random()
    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        Dim ax As Integer = 10
        For i = 1 To ax
            Dim pb As New PictureBox
            pb.SizeMode = PictureBoxSizeMode.AutoSize
            pb.Image = Image.FromFile(Application.StartupPath + "\images\buildings\base.png")
            pb.Location = New Point(RandomClass.Next(Math.Floor((Me.Width) / pb.Width)) * pb.Width, RandomClass.Next(Math.Floor((Me.Height) / pb.Height)) * pb.Height)
            Me.Controls.Add(pb)
        Next
    End Sub

Re: Add Control to a Random() location on form.

Posted: Wed Aug 22, 2012 8:31 pm
by Scottie1972
thanks guys. this gives me something to work with.