从Dictionay填充数据表 [英] Filling Datatable From Dictionay

查看:80
本文介绍了从Dictionay填充数据表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,您能帮我吗?

我需要填写一个数据表并将其设置为datagridview的数据源,我的代码如下:

Hi all can you please help me?

I need to fill a datatable and set it as a datasource for a datagridview my code is below:

private void GenerateGrid(Dictionary<string, string> staticFields) {
            DataTable dataTable = new DataTable();
            dataTable.Columns.Add(COLUMN_NAME);
            dataTable.Columns.Add(COLUMN_VALUE);
            
            int numberOfColumns = staticFields.Keys.Count;
            string[] dynamicColumns = new string[numberOfColumns];
            staticFields.Keys.CopyTo(dynamicColumns, 0);
            foreach (string columnName in dynamicColumns) {
                dataTable.Rows.Add(columnName, "");
            }
            for (int index = 0; index < dynamicColumns.Count(); index++) {
                dataTable.Rows[index][1] = staticFields[dynamicColumns[index]];
            }
            dgvDynamicColumns.DataSource = null;
            dgvDynamicColumns.DataSource = dataTable;
            dgvDynamicColumns.Refresh();


        }



尽管字典的计数为3,但datagridview为空.

请帮助



the datagridview is empty although the dictionary is of count 3.

Plz help

推荐答案

为什么不简单地执行以下操作?
Why not simply do the following?
private void GenerateGrid(Dictionary<string,> staticFields)
{
    DataTable dataTable = new DataTable();
    dataTable.Columns.Add("Name");
    dataTable.Columns.Add("Value");
    
    // Step through the KeyValuePairs in the dictionary.
    // Simply add a row for each pair in the dictionary and
    // fill the first column with the keys value
    // and the second with the values value.
    foreach (var pair in staticFields)
    {
        dataTable.Rows.Add(pair.Key, pair.Value);
    }
    
    dgvDynamicColumns.DataSource = null;
    dgvDynamicColumns.DataSource = dataTable;
    dgvDynamicColumns.Refresh();
}

对我来说似乎容易得多...顺便说一句,您的代码示例对我来说同样有效.

Seems a lot easier to me... By the way, your code sample worked just as well for me.


这篇关于从Dictionay填充数据表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆