我正在構建一個Windows窗體應用程序,它允許用戶從url下載圖像文件並將圖像設置爲picturebox,同時爲每個圖像動態創建Picturebox,兩個按鈕和一個文本框。下載圖像文件並動態創建控件C#
下面是我在的Form_Load方法使用循環現在
noofimages = no of images
imagesnames = array containing images names
uploadnumber= folder name created with images
for (int i = 0; i < Globals.noofimages; i++)
{
client = new WebClient();
string url = "http://www.upload2printer.co.il/public/uploads/" + Globals.uploadnumber + "/" + Globals.imagesnames[i] + "";
Uri uri = new Uri(url);
byte[] bytes;
bytes = client.DownloadData(uri);
MemoryStream ms = new MemoryStream(bytes);
Globals.images[i] = System.Drawing.Image.FromStream(ms);
create_controls(i);
}
Now create_controls(i) is a method responsible for creating the controls
private void create_controls(int index)
{
PictureBox pb = new PictureBox();
pb.Image = Globals.images[index];
pb.Size = new Size(200, 120);
Button b1 = new Button();
Button b2 = new Button();
TextBox noofprints = new TextBox();
b1.Size = new Size(20, 20);
b1.Name = index.ToString();
b1.Text = "+";
b1.Location = new Point(x, y + 125);
b1.Click += new EventHandler(button_Click);
b2.Size = new Size(20, 20);
b2.Text = "-";
b2.Name = index.ToString();
b2.Location = new Point(x + 180, y + 125);
b2.Click += new EventHandler(button_Click);
noofprints.Name = index.ToString();
noofprints.Size = new Size(160, 18);
if (status == 0)
{
noofprints.Text = "1";
}
else if (status == 1)
{
noofprints.Text = Globals.noofcopy[index].ToString();
}
noofprints.TextAlign = HorizontalAlignment.Center;
noofprints.Location = new Point(x + 20, y + 125);
pb.SizeMode = PictureBoxSizeMode.StretchImage;
pb.Location = new Point(x, y);
x += pb.Width + 10;
maxheight = Math.Max(pb.Height, maxheight);
if (x > this.panel1.Width - 100)
{
x = 20;
y += maxheight + 30;
}
this.panel1.Controls.Add(b1);
this.panel1.Controls.Add(b2);
this.panel1.Controls.Add(noofprints);
this.panel1.Controls.Add(pb);
}
當我運行的應用程序下載圖像文件的代碼這種形式打開表單時,所有的照片都被加載和所有控件只顯示創建。
我想要做的是下載每張照片,然後在窗體顯示時創建其各自的控件。
我也研究了多線程和異步並等待,但無法找到任何東西。
我是一名初學者和一位自學的程序員,所以我知道我的代碼並不完美,因此我希望您在解決此問題時提供幫助。
在此先感謝。
顯然你是在Form_Load事件中這樣做的。該表格將在完成此活動後出現! 在Form_Load事件中創建一個新任務,並在每個下載的圖片之後,將其添加到您的表單中。 另一個提示: 你必須修改你的控件的位置 –
也許看看https://stackoverflow.com/questions/19163966/add-controls-to-gui-in-background-worker。您希望保持UI的響應,並隨時添加一個控件,並在添加控件後立即渲染它。我認爲這是要走的路! – Digvijay