c# - 如何从另一个函数加载字符串?

标签 c# string winforms timer

我有一个带有计时器的简单表单,并在其中放置了标签。我是 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/

相关文章:

c# - 十进制值到字符串

c# - 将 csv 读取到网格的更快方法

winforms - splicer c# 指定了无效的媒体类型

c# - 如何对对象列表进行分组 C#

c# - 从C#中的继承类获取变量

c# - AvalonEdit中如何设置语法高亮?

c# - 带有 id 的 asp.net core 2 razor 页面路由

c - 使用 fgets 读取 'c' 中的文件

java - 如何将文本字段添加到 java swing 中按钮的 Action 监听器?我也有关于字符串的疑问

Python 字符串模式