A Robben
A Robben

Reputation: 309

Add Multiple Lists <T> To DataTable

I'm struggling to figure out how I can add (in my case 3 lists) to a DataTable so I can output it on my GridView.

I have the following Lists

  1. List Name (Content number of string)
  2. List Number (Content number of integers)
  3. List Status (Content number of string)

Ideally I would like to have the following result in DataTable

Name (Column 1) : Content Of List 1
Number(Column 2) : Content of List 2
Status(Column 3) : Content of List 3

I would really appreciate if someone could guide me here, as I haven't found much on the net. Please do ask if it isn't clear what I'm trying to do.

Upvotes: 1

Views: 4024

Answers (1)

Habib
Habib

Reputation: 223352

That depends on couple of things,

  • All the list have same number of items
  • The order of elements in the lists are same as well, for example, on index 0, you have Name in NameList, on index 0 of NumberList, you have relevant number and so on.

With this you can use a single loop and add rows to your DataTable (dt) like:

for (int i = 0; i < NameList.Count; i++)
{
    dt.Rows.Add(NameList[i], NumberList[i], StatusList[i]);
}

Assuming you have DataTable in place with three columns like:

DataTable dt = new DataTable();
dt.Columns.Add("Name", typeof (string));
dt.Columns.Add("Number", typeof (int));
dt.Columns.Add("Status", typeof (string));

A better approach, would be to have list of a custom object, where your object would have properties, Name, Number, Status. Populate that List, instead of maintaining three different lists based on index.

Upvotes: 1

Related Questions