top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How to retrieve all Rows of the DataTable to a List in C#?

0 votes
450 views
How to retrieve all Rows of the DataTable to a List in C#?
posted Apr 30, 2016 by Sathyasree

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes
using System;

using System.Collections.Generic;

using System.Data;

namespace AbundantCode

{

internal class Program

{

// Using Foreach to loop through datatable and retreive all rows to a List

private static void Main(string[] args)

{

List<CodeSnippet> CodeLst = new List<CodeSnippet>();

DataTable dt = new DataTable();

dt.Columns.Add("Name");

dt.Columns.Add("Code");

DataRow row1 = dt.NewRow();

row1["Name"] = "Abundantcode";

row1["Code"] = "1-1-1";

dt.Rows.Add(row1);

DataRow row2 = dt.NewRow();

row2["Name"] = "Plenty of sourcecode";

row2["Code"] = "1-1-12";

dt.Rows.Add(row2);

foreach (DataRow row in dt.Rows)

{

CodeLst.Add(new CodeSnippet { Code = row["Code"].ToString(), Name = row["Name"].ToString() });

}

foreach (var Lst in CodeLst)

{

Console.WriteLine(Lst.Name);

}

Console.ReadKey();

}

}

public class CodeSnippet

{

public string Name { get; set; }

public string Code { get; set; }

}

}
answer Apr 30, 2016 by Shivaranjini
...