如何从另一个函数加载一个字符串?(How to load a string from another function?)

编程入门 行业动态 更新时间:2024-10-20 07:52:22
如何从另一个函数加载一个字符串?(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; }

更多推荐

本文发布于:2023-08-01 19:36:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1363729.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   函数   加载   function   load

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!