所以我试图使用一个巨大的Label(位于Form1上)显示我的应用程序从Form2到Form1的进度,但Label的Text proprety并没有使用我的代码进行更改。
通过Form2执行下载过程,当它完成时,我希望更新Form1上的标签以通知用户完成。
这是代码: 在Form1中:
public string LabelText
{
get
{
return this.label1.Text;
}
set
{
this.label1.Text = value;
this.Refresh();
}
}
Form2中的:
private void DLClient(string link, string saveloc)
{
webClient = new WebClient();
webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(webClient_DownloadProgressChanged);
webClient.DownloadDataCompleted += new DownloadDataCompletedEventHandler(webClient_DownloadDataCompleted);
webClient.DownloadDataAsync(new Uri(link));
}
private void webClient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
double bytesIn = double.Parse(e.BytesReceived.ToString());
double totalBytes = double.Parse(e.TotalBytesToReceive.ToString());
double percentage = bytesIn / totalBytes * 100;
progressBar1.Value = int.Parse(Math.Truncate(percentage).ToString());
}
private void webClient_DownloadDataCompleted(Object sender, DownloadDataCompletedEventArgs e)
{
byte[] downloadedBytes = e.Result;
Stream file = File.Open(saveloc, FileMode.Create);
file.Write(downloadedBytes, 0, downloadedBytes.Length);
file.Close();
webClient.Dispose();
(new Form1()).LabelText = "Desired Text";//the changing code
Close();
我不认为Form1中Form2的调用代码有用,因为它几乎可以100%工作。
答案 0 :(得分:3)
传递Form2 Form1的实例,就像在form2的类构造函数中一样。
不要实例化一个新的(不可见的)Form1,就像你在这里做的那样:
(new Form1()).LabelText
解决方案:
private Form form1;
public Form2(Form theForm1) {
form1 = theForm1;
}
...
((Form1)form1).LabelText = "It works";
主叫代码:
Form2 frm2 = new Form2(this);
"这"是Form1实例。
答案 1 :(得分:1)
在设置标签文本时,您正在初始化Form1
的新实例,因此所需的文本实际上是在new Form1
中设置的,而不是在已打开的表单中。这是两个不同的实例,彼此不了解。
理想情况下,我会通过为此创建一个事件DownloadCompleted
或类似的事件来做到这一点;在Form2中引发事件并在Form1中处理此事件。
另一个快速选项是在Form2中拥有Form1的实例,然后您可以在显示Form2之前分配此属性。像这样的东西 -
var objForm2 = new Form2();
objForm2.objForm1 = this;
objForm2.ShowDialog();
...然后在Form2中 -
objForm1 .LabelText = "Desired Text";//the changing code