C#.Net在文本框中逐个打印字符串字符

3

我是一名新手,正在学习C#,希望您能帮助我。我想在文本框中逐个显示一个字符,这是我的代码:

private void timer1_Tick(object sender, EventArgs e)
{
    int i = 0;  //why does this don't increment when it ticks again?
    string str = "Herman Lukindo";
    textBox1.Text += str[i];
    i++; 
}

private void button1_Click(object sender, EventArgs e)
{
    if(timer1.Enabled == false )
    {
        timer1.Enabled = true;
        button1.Text = "Stop";
    }
    else if(timer1 .Enabled == true )
    {
        timer1.Enabled = false;
        button1.Text = "Start";
    }
}

1
每次计时器滴答作响时,您都将i设置为零。 - eddie_cat
2
谁给这个点了踩?这篇文章作为首次发表已经相当不错了。 - musefan
1
如果(timer1.Enabled) { } else { }... 更好的方式(带有换行) - musefan
2个回答

4

为什么这个不会在再次计时时增加?

因为你的变量i只存在于事件的本地。你需要将它定义在类级别上。

int i = 0;  //at class level
private void timer1_Tick(object sender, EventArgs e)
{
    string str = "Herman Lukindo";
    textBox1.Text += str[i];
    i++; 
}

在事件退出时,变量i超出范围并失去其值。在下一个事件中,它被视为具有初始化值0的新本地变量。
接下来,您还应该查找跨线程异常。因为您的TextBox没有在UI线程上更新。

也许可以加入一些验证...避免依赖用户在最后一个字母打印出来时点击停止按钮。 - musefan
@HermanGideon,欢迎您,也欢迎来到Stack Overflow。 - Habib
非常感谢,我已经给您发送了一封电子邮件,请查收。 - Herman Gideon
@musefan,是的,我真的需要那个。你能帮我吗?因为在最后一个字母打印出来后,我遇到了错误信息。 - Herman Gideon
@musefan 非常感谢,我从你的代码中学到了一些东西,它完美地运行了。 - Herman Gideon
显示剩余4条评论

0

你的代码问题在于每次tick时都会将i=0赋值,因此每次使用时它都是0。我建议您使用类级别变量。

然而,在类级别使用变量意味着您需要在某个时刻重置为0,可能是每次启动计时器时。

另一个问题是,您需要验证tick事件以确保不尝试访问不存在的索引(IndexOutOfRangeException)。为此,我建议在打印最后一个字母后自动停止计时器。

考虑到所有这些问题,这是我建议的代码:

int i = 0;// Create i at class level to ensure the value is maintain between tick events.
private void timer1_Tick(object sender, EventArgs e)
{
    string str = "Herman Lukindo";
    // Check to see if we have reached the end of the string. If so, then stop the timer.
    if(i >= str.Length)
    {
        StopTimer();
    }
    else
    {
        textBox1.Text += str[i];
        i++; 
    }
}

private void button1_Click(object sender, EventArgs e)
{
    // If timer is running then stop it.
    if(timer1.Enabled)
    {
        StopTimer();
    }
    // Otherwise (timer not running) start it.
    else
    {
        StartTimer();
    }
}

void StartTimer()
{
    i = 0;// Reset counter to 0 ready for next time.
    textBox1.Text = "";// Reset the text box ready for next time.
    timer1.Enabled = true;
    button1.Text = "Stop";
}

void StopTimer()
{
    timer1.Enabled = false;
    button1.Text = "Start";
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接