我想每隔1秒读取一行并将其放入文本框中。我管理了下面的代码:
private void button1_Click(object sender, EventArgs e)
{
while ((line = file.ReadLine()) != null)
{
timer.Start();
}
}
private void timer1_Tick(object sender, EventArgs e)
{
textBox1.text += line + "\r\n";
}但是line是不可访问的。我也尝试了类似这样的东西:
private void button1_Click(object sender, EventArgs e)
{
timer.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
while ((line = file.ReadLine()) != null)
{
textBox1.Text += line + "\r\n";
}
}但它忽略了计时器间隔。更重要的是,我不知道如何在这两个示例中停止计时器。你能给我点建议吗?我能用这个做什么?
编辑
有什么想法可以解释为什么这段代码可以很好地使用if,但不适合while
private void timer1_Tick(object sender, EventArgs e)
{
while ((line1 = file1.ReadLine()) != null)
{
while ((line2 = file2.ReadLine()) != null)
{
try
{
//some code
}
catch
{
//some code
}
finally
{
//some code
}
}
}
timer1.Stop();
}我希望将file2中的每一行与file1中的每一行组合在一起。
发布于 2016-07-23 06:48:27
此代码将从给定文件(当前为c:\myfile\test.xml)中提取一行并将其读入数组,然后启动计时器。一旦计时器启动,它将确定是否满足您的数据结束。如果仍然有数据,那么你将把它附加到文本框中。如果没有数据留下,计时器将停止。您可以再次按下该按钮以重新启动该过程。
//holds each line of the file contents
string[] lines = null;
//sets the current line number that you are at in the lines array
int curline = 0;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//reads all lines of files and starts the timer
lines = File.ReadAllLines(@"C:\myfile\test.xml");
curline = 0;
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
//if not end of data then insert on another line of the textbox
if (curline < lines.Length)
{
textBox1.Text += lines[curline] + "\r\n";
curline++;
}
else
{
//else stop the timer
timer1.Stop();
}
}祝你编码愉快,Jason
https://stackoverflow.com/questions/38535908
复制相似问题