2014-07-21 206 views
3

是新来的C#,我需要你的帮助,在此,我想在一个文本框,这一次显示一个字符是我的代码C#.NET打印字符串的一个字符时在TextBox

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

你设置我在每次计时器滴答时间为零。 –

+2

谁降低了这个?这是第一次发布 – musefan

+1

'if if(timer1.Enabled){} else {}'...好得多(带有换行符) – musefan

回答

0

与您代码有关的问题是您每次打勾时都会分配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"; 
} 
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线程上得到更新。

+0

可能还有一些验证在那里发生......保存依赖用户点击停止按钮时,最后一封信 – musefan

+0

非常感谢你的兄弟,并感谢你的每一个机构,我第一次问一个问题,它已被完全回答我很高兴它的工作 –

+0

@HermanGideon,欢迎您,欢迎来到堆栈溢出。 – Habib