【发布时间】:2014-08-29 19:16:06
【问题描述】:
我正在尝试使用 WinForms 应用程序中文件中的值更新我的标签文本。这是一个简单的 2-3 行文件,其中包含基于从组合框中选择的产品的 FTP 链接。
如果我使用消息框,我可以看到我实际上正在获取我正在寻找的值,但它们只是没有在屏幕上更新。
我查看了 BackgroundWorker 进程,大多数必须使用此解决方案的人都抱怨应用程序在处理操作时被锁定。我的程序没有这样做,并且在产品选择期间 100% 正常运行。
在我的 try and catch 中设置标签后,我也尝试过 ftpLabel.Refresh()/.Update() 之类的方法,但它仍然没有更新。
我什至尝试过“永远不要使用!” Application.DoEvents() 并且无法使其工作。我确信我的问题有一个更简单的解决方案,然后通过后台工作进程。我是 c# 新手,不知道如何设置它,我真的希望能找到一些有用的东西。
我的代码如下:
private async void productComboBox_SelectedItemChanged(object sender, EventArgs e)
{
// Get selected product
string selectedProduct = productComboBox.SelectedItem.ToString();
// Create the flow layout panel that will contain the links
// Display the group box and set the name
ftpGroupBox.Visible = true;
ftpGroupBox.Text = selectedProduct + " FTP Links";
// Create the flp
FlowLayoutPanel ftpFLP = new FlowLayoutPanel();
ftpFLP.Name = "ftpLinks";
ftpFLP.Dock = DockStyle.Fill;
Label ftpLabel = new Label();
ftpLabel.AutoSize = true;
try
{
using (StreamReader sr = new StreamReader(selectedProduct + ".txt"))
{
String line = await sr.ReadToEndAsync();
ftpLabel.Text = line;
ftpLabel.Update();
MessageBox.Show(line);
}
}
catch (Exception ex)
{
ftpLabel.ForeColor = Color.Red;
ftpLabel.Text = "Error: " + ex.Message;
ftpLabel.Update();
MessageBox.Show(ex.Message);
}
ftpFLP.Controls.Add(ftpLabel);
ftpGroupBox.Controls.Add(ftpFLP);
}
提前致谢。
【问题讨论】:
-
productComboBox.SelectedItem.ToString()是否返回预期值?我猜应该是productComboBox.SelectedText.ToString()。 -
你知道如何使用
async修饰符吗? -
@jAC 您应该将
label.Parent属性设置为必须出现标签的Control或ParentControl.Controls.Add(label)。 -
@Onur 奇怪的是它确实返回了预期值,但我会改变它,因为你是正确的,它会更有意义:)
-
@Reniuz 只是告诉我文件流需要它