【问题标题】:hashtable datagridview show empty lineshashtable datagridview 显示空行
【发布时间】:2013-11-24 11:30:05
【问题描述】:

我的 Datagrid 填充了正确的行数,但没有数据显示。 所有行都显示为空列。

这可能是什么原因?

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];

    }

【问题讨论】:

    标签: c# datagridview hashtable


    【解决方案1】:

    第一个例子

    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];
    }
    

    第二个例子

    假设你的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;
    

    【讨论】:

    • 您的示例当然可以,但是我在 OP 代码中找不到任何错误。它应该可以工作,事实上我已经尝试过类似的代码并且工作起来就像一个魅力。 OP在他的测试中可能有一些奇怪的地方,SO中已经发布了很多这样的问题。
    • 感谢 Tomek 的帮助和时间,我从头开始做了,现在可以完美运行了。
    猜你喜欢
    • 1970-01-01
    • 2013-10-31
    • 1970-01-01
    • 1970-01-01
    • 2017-01-17
    • 2015-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多