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

时间:2017-01-09 02:24:40

标签: 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不知道时间字符串。有人可以帮助初学者了解我如何让它起作用吗?

2 个答案:

答案 0 :(得分:2)

嗯..您可以在代码顶部声明一个私有字符串,如下所示:

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;

        }

答案 1 :(得分:1)

您可以将字符串时间变量设为全局变量,可以在任何地方访问。

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;

}