Question adding controls to a form programmatically

kfirba

Well-known member
Joined
Dec 29, 2012
Messages
77
Programming Experience
1-3
Hello!

I have a database table which contains movies information. The information stored contains the movie's name, description, photo, and an ID.

I want to display on the form the photo of the movie in a picturebox and the name of the movie in a label.

In order to display many movies, I have to use a loop that will go through each record in the table. In order to do that, I'm going to create a list of pictures and labels and create the controls. after that, I'm going to print the controls on the form.

I want to create an event to the picturebox that whenever I click the picturebox, it's gonna make a form pop and show a bigger image of the movie and the description of the movie. I want that whenever I click on the picturebox, it's gonna set a variable with the movie ID and pass it to the next form so the next form can retrieve the information about the movie and display it. Unfortunately, I have NO idea how to do it, or if it's even possible.

I would like to get help!

Thanks in advance!
 
Hi,

Here is an example of dynamically adding controls at run time. In this case I have just added the controls based on information in a sample list of information but the principals would remain the same for reading the information from your database:-

VB.NET:
Public Class Form1
  'here I create a custom class to hold the movie information
  Public Class myMovieInfo
    Public Property MovieID As Integer
    Public Property MovieName As String
    Public Property PictureFilePath As String
  End Class
  Private myMovieList As New List(Of myMovieInfo)
 
  Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    'Create some sample movie information on the form load event
    Dim Move1 As New myMovieInfo
    Dim Move2 As New myMovieInfo
    Dim Move3 As New myMovieInfo
 
    With Move1
      .MovieID = 1
      .MovieName = "Live and Let Die"
      .PictureFilePath = "d:\temp\Bee.png"
    End With
    With Move2
      .MovieID = 2
      .MovieName = "Rteurn of the Jedi"
      .PictureFilePath = "d:\temp\Bee.png"
    End With
    With Move3
      .MovieID = 3
      .MovieName = "Les Miserables"
      .PictureFilePath = "d:\temp\Bee.png"
    End With
 
    'add the movies to a list. This will simulate what is returned from your database
    With myMovieList
      .Add(Move1)
      .Add(Move2)
      .Add(Move3)
    End With
  End Sub
 
  Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    'now we can iterate the movie list and add them to the form
    For Each myMovie As myMovieInfo In myMovieList
      'defined two new controls to be added
      Dim myLabel As New Label
      Dim myPicture As New PictureBox
 
      'set the properties of the new controls
      myLabel.Text = myMovie.MovieName
      With myPicture
        .Image = Image.FromFile(myMovie.PictureFilePath)
        .Tag = myMovie.MovieID
      End With
 
      'here we add the controls to a flow layout panel to
      'manage the positioning of the controls but you could
      'explicitly set the location of the controls if you 
      'just wanted to add them to the forms controls collection
      With FlowLayoutPanel1.Controls
        .Add(myLabel)
        .Add(myPicture)
      End With
      'here we add a handler for the picture boxs click event
      AddHandler myPicture.Click, AddressOf MyPictureClickEvent
    Next
  End Sub
 
  Private Sub MyPictureClickEvent(sender As System.Object, e As System.EventArgs)
    'this is what is ran what the picturebox is clicked
    'display the movie id of the picturebox
    Dim CurrentPictureBox As PictureBox = DirectCast(sender, PictureBox)
    MsgBox(CurrentPictureBox.Tag.ToString)
 
    'open a bigger picture using a new form
    Dim myBigPicture As New Form2(Convert.ToInt32(CurrentPictureBox.Tag))
    myBigPicture.ShowDialog()
  End Sub
End Class

Hope that helps.

Cheers,

Ian
 
Wow, thanks a lot!
Is there any way I can store the movie tag in a GLOBAL variable? I will access the form that shows the detail of the movie from many different forms, so I want to set a global variable that the form that shows the details on the movie will read the global variable and get the movie information according to the global variable value. Is this possible thing to do? It's just like the sessions in PHP.

one more thing, I can use your code with unlimited movies right? I will just use a for loop to run through the table and create an object and then insert it into the list. Last time I did that, the compiler told me that I'm referencing to Null object for some reason..
If you don't mind, can you show me in your code your way to do it?

thanks in advance!
 
Hi

Is there any way I can store the movie tag in a GLOBAL variable?

Yes, just add a Module to your project and declare your variables there as Public. You can also set a variable to Public in your form which can then be accessed by other forms in your project by explicitly referencing your form. i.e Form1.MyPublicFormVariable.

one more thing, I can use your code with unlimited movies right? I will just use a for loop to run through the table and create an object and then insert it into the list. Last time I did that, the compiler told me that I'm referencing to Null object for some reason..
If you don't mind, can you show me in your code your way to do it?

Yes, you can use the code with unlimited movies. One thing to think about though is that if you have your information stored in a DataTable which has been read from your database then do you really need a separate list since your database is just a list of DataRows which can just as easily be looped through to create your controls.

At this point I do not know how you are accessing your database, so not only can I not give you an example based on what you are doing, I cannot give you any indication why you may be getting a null reference error.

Hope that helps.

Cheers,

Ian
 
maybe I don't need another list, but how can I do this directly from the table?
Lets say that my dataset name is MoviesDataset and the table name is Movies, how would you do that?
 
Hi,

You can use a For Each loop to iterate through the rows of a DatTable within a DatsSet. Once you have a DataRow of the DataTable you can then access the fields of the DataRow by referring to the name of the field or the index of the field in the DataRow.

Ignore that fact that I am using an Employees table as a demonstration but have a look here as to how this can be done:-

VB.NET:
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
  Dim sqlConn As New SqlConnection("Data Source=IANVAIO\SQLEXPRESS;Initial Catalog=NORTHWIND;Integrated Security=True")
  Dim daMovies As New SqlDataAdapter("Select * From Employees", sqlConn)
  Dim MoviesDataset As New DataSet
 
  daMovies.Fill(MoviesDataset, "Movies")
 
  For Each MovieRow As DataRow In MoviesDataset.Tables("Movies").Rows
    MsgBox(MovieRow(0).ToString)
    MsgBox(MovieRow("EmployeeID").ToString)
  Next
End Sub

You would then just use the information in your data fields to create the controls that you want to add to the form.

Hope that helps.

Cheers,

Ian
 
I have just got to my home, and it works perfectly!
There is only one slightly problem, the movie label appears on the right side of the picture like this:

http://img824.imageshack.us/img824/2333/capturezjo.jpg

I want the text to be shown on the bottom of the picture.

this is the code I used:
 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        For Each MovieRow As DataRow In MoviesDataSet.Tables("movies").Rows
            
            Dim myLabel As New Label
            Dim myPicture As New PictureBox


            
            myLabel.Text = MovieRow("movieName")
            With myPicture
                .Image = Image.FromFile(MovieRow("moviePhoto"))
                .Tag = MovieRow("ID")
                .Size = New System.Drawing.Size(150, 150)
                .SizeMode = PictureBoxSizeMode.StretchImage
            End With


           
            With FlowLayoutPanel1.Controls
                .Add(myPicture)
                .Add(myLabel)
            End With


           
            AddHandler myPicture.Click, AddressOf MyPictureClickEvent
        Next
    End Sub


    Private Sub MyPictureClickEvent(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Dim CurrentPictureBox As PictureBox = DirectCast(sender, PictureBox)
        MsgBox(CurrentPictureBox.Tag.ToString)


       
       
    End Sub
 
I already tried it, but the result was a horizontal line of the objects. How do I flip the flow layout?
And one more thing, is there a way to put 4 pictureboxes and 4 layers in 1 row and center the whole layout?

Thanks in advance!
 
Hi,

I already tried it, but the result was a horizontal line of the objects. How do I flip the flow layout?

If the height of the FlowLayoutPanel is not big enough to accommodate the objects being added to it then it will start to place objects in a horizontal format. You can overcome this be setting the AutoSize property of the FlowLayoutPanel to True.

And one more thing, is there a way to put 4 pictureboxes and 4 layers in 1 row and center the whole layout?

If I understand you correctly, other than coding the placement of the objects on the form you could design a TableLayoutPanel with multiple cells to hold your objects.

Hope that helps.

Cheers,

Ian
 
Hello! I guess that I got you a little bit confused, sorry for that.
Actually, what I'm tying to do is a form with the movies in it. The movies display has to be this way: showing 4 movies in a row and underneath each picture, put the related label. I don't want to have endless from size, so I want the panel that holds the pictures and the labels will just let the user scroll.

Hope my explanation is better now! :)

Any good idea how to do it? If you are saying a table, can you please tell me how exactly to do that?
Thanks!
 
Hi,

Firstly, you must learn to use the Internet to try and solve your problems since there is a lot that you can do with a TableLayoutPanel and sometimes a simple 2 paragraph explanation from someone on the forum does not really do justice to the control.

Have a look at this video tutorial on the net:-

Windows Forms Lesson 9 How to use the TableLayout control - YouTube

Hope that helps.

Cheers,

Ian
 
Back
Top