2013-11-24 49 views
-1

我的Datagrid填充了正確的行數,但沒有數據顯示。 所有行都顯示空的列。hashtable datagridview顯示空行

這可能是什麼原因?

basedon

這是我第一次使用一個DataGridView。

public void BindDataGridView(DataGridView dgv, Hashtable ht) { 

     DataSet ds = new DataSet(); 
     DataTable dt = ds.Tables.Add("test"); 

     //now build our table 
     dt.Columns.Add("col1", typeof(string)); 
     dt.Columns.Add("col2", typeof(Int32)); 

     IDictionaryEnumerator enumerator = ht.GetEnumerator(); 

     DataRow row = null; 

     while (enumerator.MoveNext()) { 
      string index = (string)enumerator.Key; // boekingsREf 
      MyClass a = (MyClass)enumerator.Value; 

      row = dt.NewRow(); 
      row["col1"] = index; 
      row["col2"] = a.number; 
      dt.Rows.Add(row); 
     } 

     //dgv.DataSource = ds.Tables[0]; 
     dgv.DataSource = ds.Tables[0]; 

    } 

回答

0

第一個例子

public Form1() 
{ 
    InitializeComponent(); 

    Hashtable ht = new Hashtable(); 
    ht[1] = "One"; 
    ht[2] = "Two"; 
    ht[3] = "Three"; 

    BindDataGridView(dataGridView1, ht); 
} 

public void BindDataGridView(DataGridView dgv, Hashtable ht) 
{ 
    DataSet ds = new DataSet(); 
    DataTable dt = ds.Tables.Add("test"); 

    //now build our table 
    dt.Columns.Add("col1", typeof(int)); 
    dt.Columns.Add("col2", typeof(string)); 

    foreach (DictionaryEntry dictionaryEntry in ht) 
    { 
     int index = (int)dictionaryEntry.Key; 
     string value = (string)dictionaryEntry.Value; 

     DataRow row = dt.NewRow(); 
     row["col1"] = index; 
     row["col2"] = value; 
     dt.Rows.Add(row); 
    } 

    dgv.DataSource = ds.Tables[0]; 
} 

enter image description here

第二個例子

假設你MyClass

public class MyClass 
{ 
    public int number { get; set; } 

    static public implicit operator MyClass(int value) 
    { 
     return new MyClass() { number = value }; 
    } 
} 

和哈希表(反向鍵/值)

Hashtable ht = new Hashtable(); 
ht["One"] = 1; 
ht["Two"] = 2; 
ht["Three"] = 3; 

,你從你的郵編

MyClass a = (int)enumerator.Value; 

enter image description here

+0

你當然示例工作但是我不能」改變這一行在OP代碼中找不到任何錯誤。它應該工作,事實上我已經嘗試過類似的代碼,並且像魅力一樣工作。 OP在測試中可能有些奇怪的東西,在SO中已經發布了許多這樣的問題。 –

+0

感謝您的幫助和時間Tomek,我從零開始做了它,現在它完美地工作。 – herman