我有一个带有计时器的简单表单,并在其中放置了标签。我是 c# 的新手,但设法将时间存储在一个字符串中,但我无法在加载表单期间显示该字符串,因为它位于计时器函数中...
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
timer1.Enabled = true;
timer1.Interval = 1000;
//clockLabel.Text = "00:00:00";
clockLabel.Text = time;
}
private void timer1_Tick(object sender, EventArgs e)
{
string time = DateTime.Now.ToString("hh:mm:ss"); // stored time in string
clockLabel.Text = time;
}
问题是 Form1_Load 不知道时间字符串。有人可以帮助初学者了解我如何让它工作吗?
最佳答案
嗯..你可以像下面这样在代码的顶部声明一个私有(private)字符串:
private string _time;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
timer1.Enabled = true;
timer1.Interval = 1000;
//clockLabel.Text = "00:00:00";
clockLabel.Text = _time;
}
private void timer1_Tick(object sender, EventArgs e)
{
_time = DateTime.Now.ToString("hh:mm:ss"); // stored time in string
clockLabel.Text = _time;
}
关于c# - 如何从另一个函数加载字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41540137/