2013-11-24 47 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