我試圖動態地將pictureboxes添加到C#win32窗體中,用於生產質量近乎適中的應用程序,我試圖構建它,並且我已經將它變得非常糟糕。如何通過按鈕點擊動態生成圖片框?
我遇到的問題是,我似乎無法動態地在方法中添加picturebox或控件到窗體。我已經通過Form1初始化方法將它們添加到窗體中,但是如果我在button_click方法中添加控件,它不會添加它們,除非我有面板容器,並且鍵入panel1.Controls.Add(stuff) 。但是,然後這個圖片盒出現在一個完全不同於預期的位置 - 顯然,它被面板本身擋住了。大多數的圖畫框都被面板阻擋,其中一部分是面板外側。我不知道發生了什麼事。
下面是我使用,我學會了在網上添加pictureboxes,在點擊一個按鈕方法的代碼:
PictureBox pb = new PictureBox();
pb.Size = new Size(this.Size.Width/14, this.Size.Width/12); //I use this picturebox simply to debug and see if I can create a single picturebox, and that way I can tell if something goes wrong with my array of pictureboxes. Thus far however, neither are working.
pb.BackgroundImage = Properties.Resources.cardback;
pb.BackgroundImageLayout = ImageLayout.Stretch;
pb.Location = new Point(50, 50);
pb.Anchor = AnchorStyles.Left;
pb.Visible = true;
InitializeComponent();
this.Controls.Add(pb);
PictureBox[] pbName = new PictureBox[totaldeckcount];
for (int i = 0; i < totaldeckcount; i++)
{
pbName[i] = new PictureBox();
pbName[i].Size = new Size(this.Size.Width/14, this.Size.Width/12);
pbName[i].BackgroundImage = Properties.Resources.cardback;
pbName[i].BackgroundImageLayout = ImageLayout.Stretch;
pbName[i].Image = Properties.Resources.cardback;
pbName[i].Anchor = AnchorStyles.Left;
pbName[i].Visible = true;
int x = 0;
int y = 15;
if (i > 10)
{
y += (int)((this.Size.Height * i) + 30);
}
x = (int)((this.Size.Width/12) * Math.IEEERemainder(i, 10));
pbName[i].Location = new Point(x, y);
this.Controls.Add(pbName[i]);
}
Cardback是一個工作的質感,我見過的東西彈出當我嘗試用Form1的方法制作一個picturebox,所以這不是問題。該問題不會-appear-是我的語法,因爲我能夠給
PictureBox pb = new PictureBox();
代碼直接複製到Form1的方法,它執行就好了。
我在網上找不到任何東西,這讓我完全陷入困境。
刪除'for'循環中的第二個'InitializeComponent();'調用。 – keyboardP
並刪除'pbName [i] .Parent = this;' –
@keyboardP沒有骰子,結果相同。它在那裏幾次的唯一原因是因爲我試圖讓它初始化pictureboxes,哈哈;但刪除循環中的一個沒有任何結果。按鈕點擊沒有顯示。 – Codefun64