how to read excel data without manually telling the cells

51 Views Asked by At

My code when ran, opens a form and when that form opens, it opens and reads data from a excel spreadsheet. During the initial load, it reads the specific data from it's current cells. To test the theory of reading extra data, I manually re-read the data using a button and calling specific cells. Here is my code below:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace test_read_data_from_excel
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            OpenFile();

        }

        public void OpenFile()
        {
            Excel excel = new Excel(@"Test.xlsx", 1);
            textBox1.Text = excel.ReadCell(1, 0);
            textBox2.Text = excel.ReadCell(1, 1);
            textBox3.Text = excel.ReadCell(3, 2);
            
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Form2 frm = new Form2();
            frm.Show();
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void button2_Click(object sender, EventArgs e)
        {
            Excel excel = new Excel(@"Test.xlsx", 1);
            textBox1.Text = excel.ReadCell(2, 0);
            textBox2.Text = excel.ReadCell(2, 1);
            textBox3.Text = excel.ReadCell(4 , 2);
        }
    }

}

How can I get the form to automatically read the data and then every 10 seconds display the next line or cells of data? P.S. I used a button to check to see if the reading of the next line of data or cells works correctly.

1

There are 1 best solutions below

0
mattjr747 On

For the timer functionality, try something like this:

private void InitializeTimer()  
{  
    // Call this procedure when the application starts.  
    // Set to 10 seconds.  
    Timer1.Interval = 10000; // .Interval is in milliseconds
    Timer1.Tick += new EventHandler(Timer1_Tick);  
  
    // Enable timer.  
    Timer1.Enabled = true;  
}  
  
private void Timer1_Tick(object Sender, EventArgs e)
{  
   //Call any excel code you want to run every 10 seconds here  
}