2013-09-10 75 views
1

我遇到了將數據填充到datagridview控件的問題。這是我的代碼。Datagridview無法從SQL Server CE填充數據

string sqlQuery = "SELECT * FROM Table;"; 
string source = "Data Source=E:\\Documents\\Database\\Database.sdf;" + 
       "Password=password;Persist Security Info=False;"; 

SqlCeDataAdapter dataAdapter = new SqlCeDataAdapter(sqlQuery, source); 
SqlCeCommandBuilder commBuilder = new SqlCeCommandBuilder(dataAdapter); 

DataTable table = new DataTable(); 
table.Locale = System.Globalization.CultureInfo.InvariantCulture; 

dataAdapter.Fill(table); 

dbBindSource.DataSource = table; 
dbGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader); 
dbGridView.ReadOnly = true; 
dbGridView.DataSource = dbBindSource; 

這是運行在表單加載無濟於事。任何人?

+0

您必須在調試模式下運行應用程序,並確保每行代碼按預期運行。 –

+0

如果你在'dbBindSource.DataSource = table;'處放置斷點並檢查'table.Rows.Count()',你會看到什麼? – mrtig

+0

因爲某些未知原因選擇了檢查table.Rows.Count()之後,數據會填充datagridview控件。 – Keith

回答

0
DataTable dataT; 
BindingSource bindS; 

using (SqlCeConnection yourConnection = new SqlCeConnection("Data Source=|DataDirectory|\\YourDatabase.sdf")) { 
    dataT = new DataTable(); 
    bindS = new BindingSource();  

    string query = "SELECT * FROM table01"; 
    SqlCeDataAdapter dA = new SqlCeDataAdapter(query, yourConnection); 
    SqlCeCommandBuilder cBuilder = new SqlCeCommandBuilder(dA); 
    dA.Fill(dataT); 

    bindS.DataSource = dataT; 
    DataGridView1.DataSource = bindS; 
} 

由於頁面在谷歌上的排名並且因爲它從未被回答而使用一個工作示例復活這個。

路徑相對於您的執行目錄。