首页 > 解决方案 > 使用 C# 垂直更改文本

问题描述

我计划在我的应用程序中添加此功能,它将在用户导入的标签上显示单行文本。

工作原理:用户导入一个文本文件,然后Button单击后Label文本将更改为用户导入的文本文件的第一行文本。X秒后,它将更改为第二个。基本上,它会垂直向下移动直到最后一行,然后它会停止。

List<string> lstIpAddress = new List<string>();
int nCount = 0;

private void Form1_Load(object sender, EventArgs e)
{
   timer1.Interval = 30000;
}

private void LoadBTN_Click(object sender, EventArgs e)
    {
        OpenFileDialog load = new OpenFileDialog();
        if (load.ShowDialog() == DialogResult.OK)
        {
            listBox1.Items.Clear();

            load.InitialDirectory = Environment.SpecialFolder.Desktop.ToString();
            load.Filter = "txt files (*.txt)|*.txt";
            List<string> lines = new List<string>();
            using (StreamReader r = new StreamReader(load.OpenFile()))
            {
                string line;
                while ((line = r.ReadLine()) != null)
                {
                    listBox1.Items.Add(line);

                }
            }
        }
    }

 private void button1_Click(object sender, EventArgs e)
 {
        for (int nlstItem = 0; nlstItem < lstIpAddress.Count; nlstItem++)
            {
                listBox1.Items.Add(lstIpAddress[nlstItem]);
            }
            label2.Text = listBox1.Items[nCount].ToString();
            nCount++;
            timer1.Start();
 }

 private void timer1_Tick(object sender, EventArgs e)
 {
        timer1.Stop();
        label2.Text = listBox1.Items[nCount].ToString();
        timer1.Start();
 }

标签: c#.netwinforms

解决方案


您需要移动nCount++;到 Timer1 点击事件。此外,您应该检查是否nCount在范围内,listBox1.Items.Count否则您将获得异常。

private void timer1_Tick(object sender, EventArgs e)
        {
            timer1.Stop();
            nCount++;
            if (nCount < listBox1.Items.Count)
            {
                label2.Text = listBox1.Items[nCount].ToString();
            }
            timer1.Start();
        }

推荐阅读