简体   繁体   中英

Vertically changing text using C#

I'm planning to add this feature on my application where it will display a single line of text on a label which the user imported.

How it works: The user imports a text file, then after a Button click the Label text will change to the first line of text on the text file that the user imported. After X amount of seconds, it will change to the second one. Basically, it will move vertically down until the last line then after it will stop.

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();
 }

You need to move nCount++; to a Timer1 click event. Also, you should check if nCount is in range of listBox1.Items.Count otherwise you will get an exception.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM