6
Reply

Read data from Excel to datagridview

Baris Turkoglu

Baris Turkoglu

Apr 27 2012 5:58 AM
1.9k
I want to get all the data in a excel sheet and put it in a datagridview to be able to get specific information from the excel file. This will later be sent to a web service, but right now I only have problems to add the data to datagridview so I can see the data easier. The problem is that when I debug, I see that the program never enters the "foreach" iteration.

        private void xlsWatcher_Created(object sender,
                        System.IO.FileSystemEventArgs e)
        {
            string VIN;
            string modelCode;
            string[] optionCodes;
            int rowNr = 5;
            int nrOfOptions = 0;

            OleDbConnection conn = new System.Data.OleDb.OleDbConnection(("provider=Microsoft.Jet.OLEDB.4.0; " + ("data source=" + e.FullPath +"; " + "Extended Properties=Excel 8.0;")));
            OleDbDataAdapter ada = new OleDbDataAdapter("select * from [Rapport 1$]", conn);
            DataSet ds = new DataSet();
            ada.Fill(ds);
            dataGridView1.DataSource = ds.Tables[0];

            conn.Close();
           
            // Access particular cells on DataGridView.
            foreach (DataGridViewRow row in dataGridView1.Rows) /////JUMPS OVER THIS ITERATION!!!!!!
            {
                VIN = dataGridView1.Rows[rowNr].Cells[1].ToString();
                modelCode = dataGridView1.Rows[rowNr].Cells[2].ToString();
                //Count all the optionCodes that is on the row
                if (dataGridView1.Rows[rowNr].Cells[3].Value != DBNull.Value)
                {
                    optionCodes = new string[5];
                    optionCodes[0] = dataGridView1.Rows[rowNr].Cells[3].ToString();
                    nrOfOptions += 1;
                    optionCodes[1] = dataGridView1.Rows[rowNr].Cells[4].ToString();
                    nrOfOptions += 1;
                    optionCodes[2] = dataGridView1.Rows[rowNr].Cells[5].ToString();
                    nrOfOptions += 1;
                    optionCodes[3] = dataGridView1.Rows[rowNr].Cells[6].ToString();
                    nrOfOptions += 1;
                    optionCodes[4] = dataGridView1.Rows[rowNr].Cells[7].ToString();

                    string[] elOptions = optionCodes[4].Split(new Char[] { ' ' });
                    nrOfOptions = nrOfOptions + elOptions.Length;
                    MessageBox.Show(Convert.ToString(elOptions.Length));
                }
            }
        }

Thank you in advance.

Baris

Answers (6)