简体   繁体   中英

How can I add data from class properties into a datatable

I currently have a class with 4 properties

public class DataEntry
{
    public string Name { get; internal set; }
    public string Version { get; internal set; }
    public string TotalDownloads { get; internal set; }
    public string LastUpdated { get; internal set; }
}

I form a ConcurrentQueue of objects (using the previous classes properties)

var list = new ConcurrentQueue<DataEntry>();

foreach (var i in Enumerable.Range(0, 2))
{
    list.Enqueue(new DataEntry { Name = "TestName", Version = "Test Version", TotalDownloads = "TestDownloads", LastUpdated = "LestDate" });
}

I then return this ConcurrentQueue as a list

return list.ToList();

I am trying to populate a windows form datagridview with this data.

I understand that it is possible to populate the datagridview like this

DataGrid.DataSource = Class.Function();

However I would like to use a datatable as the datagridviews datasource.

To try and put this data into a datatable I have tried

private DataTable dataTable = new DataTable("dataTable");

private async void Form1_Load(object sender, EventArgs e)
{
    dataTable.Columns.Add("Name", typeof(string));
    dataTable.Columns.Add("Downloads", typeof(string));
    dataTable.Columns.Add("Updated", typeof(string));
    dataTable.Columns.Add("Version", typeof(string));

    foreach (var item in await Class.Function())
    {
        dataTable.Rows.Add(item);
    }

    dataGrid.DataSource = dataTable;

}

However this just puts all the data into the first column (along with the class name DataEntry at the front of the string)

How could I format the data into a datatable?

Using @o_O's advice I managed to modify the for loop to do exactly what I wanted

foreach (var item in await Class.function())
        {
            dataTable.Rows.Add(item.Name, item.TotalDownloads, item.LastUpdated, item.Version);
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM