从数组加载列表 [英] Load a list from an array

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

问题描述

我有一个正在运行的程序,除了我的数据包含在数组中之外;但是,我从您那里发现人们无法从数组加载dataGridView.
如果我有这样的代码,如何为dataGridView1的源加载一个列表...

I have a program that is working except that my data is contained in an array; however, I have found out from you people that I cannot load a dataGridView from an array.
If I had code like this, how would I load a List for the source of the dataGridView1...

        // Load some date to indicate what I'm trying to do.

        int nColName = 0;
        int nColNumberOfOccurances = 1;
        int nColTotalTime = 2;
        int nColAverageTime = 3;
        string[,] strMyArray = new string[2,4];

        // load array with test data
        for (int i = 0; i < strMyArray.Length; i++)
        {
            switch (i)
            {
                case 0:
                 strMyArray.SetValue("file1.log".ToString(), i, nColName);
                 strMyArray.SetValue("10".ToString(), i, nColNumberOfOccurances);
                 strMyArray.SetValue("8989".ToString(), i, nColTotalTime);
                 strMyArray.SetValue("898.9".ToString(), i, nColAverageTime);
                 break;
                case 1:
                 strMyArray.SetValue("file2.log".ToString(), i, nColName);
                 strMyArray.SetValue("5".ToString(), i, nColNumberOfOccurances);
                 strMyArray.SetValue("4494.5".ToString(), i, nColTotalTime);
                 strMyArray.SetValue("898.9".ToString(), i, nColAverageTime);
                    break;
            }

        }

        // convert an array like the above into a List so that I can say...
       // myNewListFromArray = strMyArray
      //  dataGridView1.DataSource = myNewListFromArray;

推荐答案

数组与DataGridView一起使用.您的问题是-您使用的二维数组不能用作数据源.

Arrays works with DataGridView. Your problems is - you using two dimensional array which cannot be used as DataSource.

创建一个具有表示您的数据的属性的类,而不是数组.
注意:使用属性很重要,因为DataGridView绑定仅适用于属性.

Instead of array, create a class with properties which represent your data.
Note: important to use a property, because DataGridView binding works with properties only.

public class MyData
{
    public string Name { get; set; }
    public string NumberOfOccurances { get; set; }
    public string TotalTime { get; set; }
    public string AverageTime { get; set; }
}

然后在列表中使用此类

var list = new List<MyData>
{
    new MyData 
    { 
        Name = "file1.log",
        NumberOfOccurances = "10",
        TotalTime = "8989",
        AverageTime = "898.9"
    },
    new MyData 
    { 
        Name = "file2.log",
        NumberOfOccurances = "5",
        TotalTime = "4494.5",
        AverageTime = "898.9"
    },
}

dataGridView1.DataSource = list;

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

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