该名称在当前上下文C#中不存在
本文关键字:上下文 不存在 | 更新日期: 2023-09-27 18:29:33
我的代码中有一个错误,它显示the name "line" does not exist in current context
。我知道原因,因为string[] lines = File.ReadAllLines(openFileDialog1.FileName);
没有在public void timer1_Tick(object sender, EventArgs e)
内部声明,但我不知道如何解决这个问题,因为我是C#的新手。我已经搜索了论坛并在谷歌上搜索了它,但我似乎找不到任何适合我的情况的东西,我知道这可能真的很简单。
下面是我的代码片段,其中的问题是:
public void button13_Click(object sender, EventArgs e)
{
string[] lines = File.ReadAllLines(openFileDialog1.FileName);
timer1.Start();
}
public void timer1_Tick(object sender, EventArgs e)
{
int lineNumber = richTextBox1.GetLineFromCharIndex(richTextBox1.TextLength);
try
{
for (int i = 0; i < lineNumber; i++)
{
if (lines[i].Contains("LCD"))
{
label1.Text = lines[i].Remove(0, 6);
}
if (lines[i].Contains("laser") && lines[i].Contains("On"))
{
pictureBox4.Show();
}
if (lines[i].Contains("laser") && lines[i].Contains("Off"))
{
pictureBox4.Hide();
}
if (lines[i].Contains(".end"))
{
button2.PerformClick();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Form3", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
我知道我可以把string[] lines = File.ReadAllLines(openFileDialog1.FileName);
放在public void timer1_Tick(object sender, EventArgs e)
中,但它每次只读取文档的第一行。
这个怎么样?
private string[] lines;
public void button13_Click(object sender, EventArgs e)
{
lines = File.ReadAllLines(openFileDialog1.FileName);
timer1.Start();
}
在这里,我们已经声明了lines
数组,使其具有类作用域。但是我们在button13_Click
事件处理程序中初始化它。