[英]DataGridView.Rows.Count is 0
我正在嘗試讀取excel文件的內容(我必須處理數據而不顯示它),但是行數是0。我確實在UI中顯示了數據,並且行沒有數字。
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?
我如何解決它?
試試看
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;
嘗試這個:
BindingSource bindingSource = new BindingSource();
bindingSource.DataSource = resultDt;
在您的情況下:
bindingSource.DataSource = ds.Tables[0];
和:
dgResult.DataSource = bindingSource;
flowLayoutPanel.Controls.Add(dgResult);
var c = dgResult.Rows.Count;
綁定源負責將數據與控件同步。 您要使用它,而不是嘗試將表直接分配給控件。
參考:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.