C# - 如何动态创建进度条

时间:2014-08-18 15:46:59

标签: c# winforms progress-bar webclient dynamically-generated

我正在尝试开发一个可以同时支持多个上传的小程序。但是,我遇到了一个问题:如果我上传了一个文件,则会有一个进度条;但是当我上传更多文件时,我不知道如何独立创建每个文件的进度条,以及如何在多个上传中自动添加其他栏。 我将WebClient类与UploadFileAsync一起使用。

String file是上传所需的路径,uploadFormForm,我会在其中显示进度条并上传。

编辑:使其正常运行的最终代码

private void UploadEnProgres(object sender, UploadProgressChangedEventArgs e, String file, ProgressBar nouvelleProgressBar)
{
    Console.WriteLine("{0} : {1} octet sur {2} au total. {3} % envoyés...", file, e.BytesSent, e.TotalBytesToSend, e.ProgressPercentage);
    nouvelleProgressBar.Value = (int)((e.BytesSent * 100) / e.TotalBytesToSend);
}

private void UploadFini(object sender, UploadFileCompletedEventArgs e, String file, ProgressBar nouvelleProgressBar, TextBox nouvelleTextBox, Int32 hauteur)
{
    if ((e.Cancelled) || (e.Error != null))
    {
        Console.WriteLine("{0} : ERREUR -- {1}", file, e.Error);
        return;
    }
    Console.WriteLine("{0} : upload terminé, statut : ", file, System.Text.Encoding.UTF8.GetString(e.Result));
    uploadForm.Controls.Remove(nouvelleProgressBar);
    uploadForm.Controls.Remove(nouvelleTextBox);
    hauteur = 12;
}

public void HTTPClientUpload(String file)
{
    Console.WriteLine("Upload button.");
    WebClient clientUpload = new WebClient();
    String authInfo;
    authInfo = utilisateur + ":" + motDePasse;
    authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
    clientUpload.Headers["Authorization"] = "Basic " + authInfo;

    // CODE HTTP UPLOAD

    this.hauteur += 22;

    ProgressBar nouvelleProgressBar = new ProgressBar();
    nouvelleProgressBar.Size = new Size(180, 20);
    nouvelleProgressBar.Maximum = 100;
    nouvelleProgressBar.Minimum = 0;
    nouvelleProgressBar.Location = new Point(258, hauteur);
    nouvelleProgressBar.Visible = true;
    uploadForm.Controls.Add(nouvelleProgressBar);

    TextBox nouvelleTextBox = new TextBox();
    nouvelleTextBox.Size = new Size(180, 20);
    nouvelleTextBox.Location = new Point(70, hauteur);
    nouvelleTextBox.Text = Path.GetFileName(file);
    nouvelleTextBox.Enabled = false;
    uploadForm.Controls.Add(nouvelleTextBox);

    clientUpload.Headers.Add("Chemin", "/" + identifiantAppareil + file.Replace(@"\", "/"));
    clientUpload.UploadFileCompleted += new UploadFileCompletedEventHandler((sender, e) => UploadFini(sender, e, Path.GetFileName(file), nouvelleProgressBar, nouvelleTextBox, hauteur));
    clientUpload.UploadProgressChanged += new UploadProgressChangedEventHandler((sender, e) => UploadEnProgres(sender, e, Path.GetFileName(file), nouvelleProgressBar));
    clientUpload.UploadFileAsync(new Uri(urlServeur, "v1/ul"), file);
}

2 个答案:

答案 0 :(得分:3)

//Create a new progressbar each time you start an upload in code
var progressbar = new ProgressBar()

//add it to the form
uploadForm.Controls.Add(progressbar );

您需要了解如何对其进行分组/定位

答案 1 :(得分:0)

对于组织,我建议使用TableLayoutPanel将新创建的控件添加到。