DataGridView.Rows.Count is 0

后端 未结 2 956
迷失自我
迷失自我 2021-01-28 16:03

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 num

相关标签:
2条回答
  • 2021-01-28 16:48

    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

    0 讨论(0)
  • 2021-01-28 16:52

    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;
    
    0 讨论(0)
提交回复
热议问题