2014-01-22 249 views
0

如何將數據綁定到datagridview?綁定到datagridview

DataTable table = new DataTable(); 
string pot = "Provider=Microsoft.Ace.OLEDB.12.0; Data Source = " + textbox_path.Text + ";Extended Properties=\"Excel 8.0; HDR=Yes;\";"; 
OleDbConnection pove = new OleDbConnection(pot); 
OleDbDataAdapter myDataAdapter = new OleDbDataAdapter("Select * from [" + textbox_sheet.Text + "$]", pove); 
DataTable dt = new DataTable(); 
myDataAdapter.Fill(dt); /* napaka | oldedb driver ? :O*/ 
dataGridView1.DataSource = dt; 
+0

您是否收到錯誤消息?數據表中有多少行。根據我的經驗,即使表格是空的,列標題也會加載。你有這些嗎? – wruckie

+0

我修正了它:)你的幫助。 – user3218707

+0

你能分享一下嗎?有人會在我們後面遇到同樣的問題,並且不知道該怎麼做。張貼您的答案並將其標記爲答案。 – wruckie

回答

0

結尾處加上: -

dataGridView1.DataBind(); 
0

如果您在Web應用程序的工作,你有dataGridView1.DataSource = dt;後添加dataGridView1.DataBind();

否則告訴我們上面的代碼中有什麼問題?它拋出任何錯誤?

+0

System.Windows.Forms.DataGridView'不包含'DataBind'的定義,並且沒有找到接受'System.Windows.Forms.DataGridView'類型的第一個參數的擴展方法'DataBind'(你是否缺少using指令或裝配參考?) – user3218707

+0

您正在使用哪個平臺? Web還是Windows?我認爲它的窗口根據錯誤消息,所以不需要DataBind()。只有當你分配源碼足夠你已經在做。那麼你的代碼有什麼問題? – Naveen

+0

我看到我不需要在Windows窗體中綁定。我需要這個工作,這傢伙說我需要綁定數據到datagrid。 http://stackoverflow.com/questions/21255274/compare-datagridview1-and-datagridview2-and-mark-same-values-c-sharp – user3218707

0

你雖然沒有提到它,這個問題被標記爲的WinForms。 Winforms不需要
dataGridView1.DataBind();
你沒有給我們任何錯誤或提示失敗的地方。我懷疑它是在這個連接字符串或select語句的形成。將數據表綁定到DGV的代碼是正確的

string pot = "Provider=Microsoft.Ace.OLEDB.12.0; Data Source = " + textbox_path.Text + ";Extended Properties=\"Excel 8.0; HDR=Yes;\";"; 
OleDbConnection pove = new OleDbConnection(pot); 
OleDbDataAdapter myDataAdapter = new OleDbDataAdapter("Select * from [" + textbox_sheet.Text + "$]", pove);