2017-01-30 167 views
0

我搜索了Web和Stack Overflow,發現了很多關於如何用DataTable的內容填充DataGridView的描述。但它仍然不適用於我。我的DataGridView顯示正確的列數和行數,但它們顯示爲空。C#:用DataTable填充DataGridView創建空表

我用下面的方法:

public void ShowDataInGrid(ref DataTable table) 
    { 
     BindingSource sBind = new BindingSource(); 
     dbView.Columns.Clear(); 
     dbView.AutoGenerateColumns = false; 
     sBind.DataSource = table; 
     dbView.DataSource = sBind; //Add table to DataGridView 
     dbView.Columns.Add("Date", "Date");    
    } 

在此之前我通過設計器創建的名爲 「dbView」 一個DataGridView。我甚至不確定,我是否需要sBind。沒有它,我可以將表直接綁定到dbView,但結果相同。

我懷疑我的表是問題所在。它起源於一個數據庫(SQLite),並有多個列和行(其中一列的名稱爲「Date」)。它確實充滿了可讀的數據。 我主要讀表中使用下列命令(在此之後我操縱在幾個不同步驟中的數據,如改變字符串和添加數字...):

 string sql = "select * from Bank"; 
     SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection); 
     SQLiteDataReader reader = command.ExecuteReader(); 
     table.Load(reader); 
     reader.Close(); 
     table.AcceptChanges(); 

我想問題可能是,該表條目存儲爲對象而不是字符串,因此無法顯示。這就是爲什麼我試圖迫使內容是字符串有以下改變我的表:

DataTable dbTableClone = new DataTable(); 
dbTableClone.Load(reader); 
SQLiteDataReader reader.Close(); 
dbTableClone.AcceptChanges(); 

string[] dBHeader = new string[dbTableClone.Columns.Count]; 
dBHeader = ReadHeaderFromDataTable(dbTableClone); //own funktion, which reads the header 
DataTable table; 
table.Clear(); 
//will first create dbTable as empty clone, so I can set DataTyp of each Column 
table = dbTableClone.Clone(); 
for (int col = 0; col > dBHeader.Length; col++) //first set all columns as string 
{ 
    dbTable.Columns[col].DataType = typeof(string); 
} 
foreach (DataRow Row in dbTableClone.Rows) 
{ 
    dbTable.ImportRow(Row); 
} 

這對我沒有幫助也沒有。 另一個想法:我發現了一些關於類似問題的評論,其中引用了明顯的解決方法:「我設計了VS數據視圖設計器中的列,而不是列名,但DataPropertyName列必須與數據庫中的字段匹配。不幸的是,我似乎無法做到/理解這一點。

以下您看到我的輸入表的一行。

enter image description here

+0

你可以簡短而準確地定義你的問題嗎? –

+0

DataViewTable顯示具有正確行數(與綁定表相同)但沒有內容的表。每個單元格都是空的。 – Birk

+0

您是否看到該表在執行查詢後有數據?'table.Load(reader);' –

回答

0

我解決了這個問題。 DataTable很好。問題是我的DataGridView dbView的設置。我在設計器中設置了dbView,並以某種方式給它一個數據源。現在我將數據源設置爲「無」(在「DataGridView任務」中),我的數據按預期顯示。 感謝M Adeel Khalid看我的東西。他向我保證,我的鏈接代碼是正確的,最終讓我找到了解決方案。 最後,我真的只需要使用一條線:

dbView.DataSource = table; 
0

嘗試獲取和設置的GridView這樣到目前爲止你做過

 SqlLiteConnection con = new SqlLiteConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=DB.mdf;Integrated Security=True"); 
     con.Open(); 
     SqlLiteDataAdapter adap = new SqlLiteDataAdapter("select * from Bank", con); 
     DataSet ds = new System.Data.DataSet(); 
     adap.Fill(ds); 
     dataGridView1.DataSource = ds.Tables[0]; 

評論的一切,試試這個,讓我知道,如果這對你的作品或沒有。根據您的數據庫更改連接。

+0

我已經用你的代碼創建了一個新的測試()。唯一需要改變的是@「Data Source = ** test.sqlite **; AttachDbFilename = DB。mdf; Integrated Security = True「); - > ds被填充(可以在調試模式下看到它),但dataGridView1沒有填充(甚至沒有空單元格) - >我添加了dataGridView1.Columns.Add(」日期」,‘日期’);這樣,我又得到細胞進入的觀點,但他們仍然是空 – Birk

+0

你能有些卡內分享你的表的結構和數據 –

+0

好吧,我加入一行的快照我?數據表到原來的職位。 – Birk