从文件中读取时,c#标签不会更新
本文关键字:标签 更新 文件 读取 | 更新日期: 2023-09-27 18:19:53
我正在尝试使用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);
}
提前谢谢。
好吧,我想我明白这里出了什么问题:)
当你第一次运行代码时,一切都很好,它按预期工作-你添加了FlowLayoutPanel
、Label
等。但第二次你再次创建新的FlowLayoutPanel并在添加它之后…不知何故,你会在看不到它的地方看到表单中的第一个FlowLayoutPanel。
因此,您需要做的是用Label
删除以前创建的FlowLayoutPanel
或重用它
编辑:
要动态添加FlowLayoutPanel
并重用它,您可以这样做(只是绘制想法,而不是实际代码):
//Create local variable of panel
FlowLayoutPanel yourPanel;
private async void eventHandler()
{
//this will create new panel if it is not existing currently
if(yourPanel == null)
{
yourPanel = new FlowLayoutPanel();
//add new control
}
Label yourLabel = new Label();
//here you use newly created or reuse previously created panel
yourPanel.Controls.Add(yourLabel);
}
如果你想重复使用标签,只需对标签使用相同的想法。