Search code examples
c#.netwinformsparent

Dynamic label parent not working


I'm creating a chat program and for the chatbox i want there to be a whatsapp kind of style message layout. My way of doing it (probably not the best) is by creating a picturebox dynamically with my blue background picture in it and then adding a label , making the picturebox the parent and then overlay the message over the picture box. I'm using this bit of code :

private void CreateChatBox(int height, string message)
    {
        PictureBox pb = new PictureBox();
        Label pbl = new Label();
        pb.Name = height.ToString();
        pbl.Text = message;
        pbl.Name = height.ToString();
        pb.Image = LocalChat.Properties.Resources.ChatBox_Test;
        pb.SizeMode = PictureBoxSizeMode.StretchImage;

        // set picturebox possitions and margins
        pb.Left = 15;
        pb.Top = 100;
        pb.Width = 250;
        pb.Height = 75;
        tabPage.Controls.Add(pb);

        //set label positions and margins
        pbl.Parent = pb;
        pbl.AutoSize = true;
        pbl.Width = 200;
        pbl.BackColor = Color.Transparent;
        pbl.Location = new Point(1, 1);
        // Add button click event Handler and add buttons and lables to the panel

        tabPage.Controls.Add(pbl);
    }

my problem is that i'm making the picturebox the parent of the label, yet the label will just sit on the very top left of the form and not inside the picturebox as i want. Am i not getting what parent should be doing? or how do i get my label to be confined inside the picturebox?


Solution

  • You must remove your line of code

     tabPage.Controls.Add(pbl);
    

    at the end of the file because after you set the parent of the label to the PictureBox you're setting its parent to the TabPage, again When you use anyControl.Controls.Add(otherControl) you're setting the otherControl.Parent to anyControl

    But i'll say that if you want that kind of control settings you should instead of dynamically creating and setting its control you could create an usercontrol and inside the usercontrol you would put the logic to the display of the message, and you could dinamically create the userControl and put it anywhere you would like