【发布时间】:2017-08-16 09:01:01
【问题描述】:
我是 C# 新手,我需要覆盖 windows 窗体上的标签。我正在使用循环根据 n 的值生成标签数量。
问题:如果我在运行程序时更改lines[i] 的值,该值确实会更改但不会在 Windows 窗体上更新(以前的值不会被新值替换)。
谁能指导我如何做到这一点?
我还使用计时器每秒刷新一次代码,这也可以正常工作
这是我创建标签并在其中写入值的部分,它处于循环中
Label label = new Label();
label.Text = String.Format("{0}", lines[i]);
label.Left = 10;
label.Top = (i + 1) * 25;
this.Controls.Add(label);
这是我的完整代码 ID,任何人都需要检查它:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace Admin
{
public partial class Form1 : Form
{
string pathuser = @"//192.168.2.10/Shared-Public/Users.txt";
int check = 0;
public static string usernam;
string[] lines = new String[500];
string[] lines2 = new String[500];
public Form1()
{
InitializeComponent();
}
private void timer_Tick(object sender, EventArgs e)
{
tc = tc + 1;
Console.WriteLine(tc);
int c = 2;
int u = 0;
int us = 0; //for user pass
int z = 0; // for reading values from file
using (StreamReader sr2 = new StreamReader(pathuser))
{
string line;
while ((line = sr2.ReadLine()) != null)
{
lines[us] = line;
us++;
}
}
for (int i = 0; i < us; i++)
{
//Create label
Label label = new Label();
label.Text = String.Format("{0}", lines[i]);
//Position label on screen
label.Left = 10;
label.Top = (i + 1) * 25;
Label label2 = new Label();
label2.Left = 120;
label2.Top = (i + 1) * 25;
string line2;
string path = "//192.168.2.10/Shared-Public/" + lines[i] + DateTime.Now.ToString(" MM-dd-yyyy") + ".txt";
if (!File.Exists(path))
{
lines2[z] = null;
}
else
{
using (StreamReader sr3 = new StreamReader(path))
{
while ((line2 = sr3.ReadLine()) != null)
{
lines2[z] = line2;
z++;
}
}
label2.Text = String.Format("{0}", lines2[0]);
u = z;
z = 0;
}
PictureBox picbox = new PictureBox();
picbox.Location = new Point(240, 25 + (i*25));
picbox.Size = new Size(15, 15);
if (u%2==0)
picbox.BackColor = Color.Green;
else
picbox.BackColor = Color.Red;
u = 0;
this.Controls.Add(label);
this.Controls.Add(label2);
this.Controls.Add(picbox);
}
}
int tc = 0;
private void Form1_Load(object sender, EventArgs e)
{
Timer timer = new Timer();
timer.Interval = (1000);
timer.Tick += new EventHandler(timer_Tick);
timer.Start();
}
}
}
【问题讨论】:
-
如果您创建要手动更改的标签,您需要在表单上的变量中保留它。然后,当您想要更改它时,您可以通过变量访问标签并进行更改。但是,您可能做错了其他事情。运行您的应用程序,看看您是否可以在您的代码每秒刷新时移动表单。我敢打赌你的 UI 没有响应,amirite?
-
您可以为
Label指定一个包含i的名称,例如label.Name = "label_" + i;。那么当你更新list[i]时也更新Controls["label_" + i].Text = list[i]; -
如果我在从中读取值的文件中添加一个新值,它会将其添加到表单中,但如果我编辑相同的值,它不会替换它.....
-
@Mubi 阅读:Bind a label to a “variable”
-
@我可以在每秒刷新的同时移动表单吗? lines[i] 中的偶数值被更改(通过在控制台中写入来尝试)
标签: c# winforms label overwrite