如何从另一个函数加载一个字符串?(How to load a string from another function?)
我有一个带计时器的简单表格,我放置了一个标签。 我是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不知道时间字符串。 有人可以帮助初学者了解我如何让它起作用吗?
I have a simple form with a timer and where I placed a label. I am new to c# but managed it to store time in a string, but I can't show this string during the load of the form since it sits in the timer function...
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; }The problem is that Form1_Load doesn't know the time string. Can someone help a beginner to understand how I can get it to work?
最满意答案
您可以将字符串时间变量设置为Global Variable,它可以在任何地方访问。
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"); clockLabel.Text = time; }You can make the string time variable to Global Variable which could be access anywhere.
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"); clockLabel.Text = time; }更多推荐
发布评论