I am dynamically trying to add a button inside a groupbox, however the button stays behind the groupbox tool and can not be seen or can not be clicked. I need my button to be seen and clickable inside of the groupbox. Here is my code:
namespace HarryPotter
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
GroupBox grp = new GroupBox();
grp.Top = 600;
grp.Left = 0;
grp.Text = "Kontroller";
grp.Size = new Size(600, 400);
//grp.BackgroundImage = Properties.Resources.hogwartscastle;
//grp.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
grp.FlatStyle = FlatStyle.Flat;
this.Controls.Add(grp);
Button btn2 = new Button();
btn2.Size = new Size(40, 40);
btn2.Top = 580;
btn2.Left = 0;
btn2.Parent = grp;
btn2.BackgroundImage = Image.FromFile(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) @"\DownArrow.png");
btn2.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
grp.Controls.Add(btn2);
this.Controls.Add(btn2);
}
}
}
CodePudding user response:
First of all, the GroupBox
is only 400 pixels tall but the Button
has its top at y location 580. So the button is there but its not visible. So either make the groupbox taller or change the btn2.Top
. Also you need to create the Click event handler for btn2
with the following: btn2.Click = Btn2_Click
then define the Btn2_Click
function.
Edit: as Reza pointed out, you need to remove the this.Controls.Add(btn2);
line as well since that will remove the button from the group box.