Add Control to a Random() location on form.

If you need help with a project or need to know how to do something specific in VB.NET then please ask your questions in here.
Forum rules
Please LOCK your topics once you have found the solution to your question so we know you no longer require help with your query.
4 posts Page 1 of 1
Contributors
User avatar
Scottie1972
Codenstuff Elite
Codenstuff Elite
Posts: 953
Joined: Thu Jan 14, 2010 5:48 am

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
Image
User avatar
M1z23R
VIP - Donator
VIP - Donator
Posts: 622
Joined: Tue Sep 28, 2010 4:55 pm

I made this, i think you can edit it to your needs...
You do not have the required permissions to view the files attached to this post.
User avatar
CodenStuff
Site Admin
Site Admin
Posts: 4392
Joined: Tue Aug 04, 2009 1:47 am

#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
Welcome to CodenStuff.com Learn Code, Love Code. Thank you for being a member of the community.
User avatar
Scottie1972
Codenstuff Elite
Codenstuff Elite
Posts: 953
Joined: Thu Jan 14, 2010 5:48 am

thanks guys. this gives me something to work with.
Image
4 posts Page 1 of 1
Return to “Coding Help & Support”