0

I'm trying to read the content of an excel file (I must process the data not show it) but the number of rows is 0. I did show the data in the UI and the rows didn't have a number.

string src = "the path;";
OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + src +
                                       "Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\"");

OleDbDataAdapter da = new OleDbDataAdapter("select * from [RENNES4_wk13$]", con);

DataSet ds = new DataSet();
da.Fill(ds);
DataGridView dgv = new DataGridView();
dgv.DataSource = ds.Tables[0];
int rows = dgv.Rows.Count;
int cells = dgv.Rows[0].Cells.Count;//ArgumentOutOfRange why?

How do I fix it?

Jay Bhalodi
  • 387
  • 3
  • 19
Mihai Bratulescu
  • 1,915
  • 3
  • 27
  • 43

2 Answers2

3

Try this out

        string src = @"C:\SampleData\us-500.xls";
        OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + src +
                                          ";Extended Properties=Excel 8.0;");

        //con.Open();
        OleDbDataAdapter da = new OleDbDataAdapter("select * from [MySheet$]", con);
        DataSet ds = new DataSet();
        da.Fill(ds);

        BindingSource bindingSource = new BindingSource();
        bindingSource.DataSource = ds.Tables[0];

        var dataGridView1 = new DataGridView();

        // Add data grid view as child control on form, flow Layout Panel is placed on windows form 
        flowLayoutPanel1.Controls.Add(dataGridView1);

        dataGridView1.DataSource = bindingSource;
        int rows = dataGridView1.Rows.Count;
        int cells = dataGridView1.Rows[0].Cells.Count;
Usama Khalil
  • 436
  • 1
  • 4
  • 14
1

try this:

BindingSource bindingSource = new BindingSource();
bindingSource.DataSource = resultDt;

in your case:

bindingSource.DataSource = ds.Tables[0];

and:

dgResult.DataSource = bindingSource;
flowLayoutPanel.Controls.Add(dgResult); 

var c = dgResult.Rows.Count;

The binding source is what's responsible for syncing your data with the control. You want to use it, rather than trying to assign the table directly to the control.

Reference:

Datagridview rowcount showing 0 even when there is a valid datasource

Community
  • 1
  • 1
Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160