1. Create a DataTable object
/// <summary> /// Create DataTable object/// </summary> public static DataTable CreateDataTable() { //Create DataTable DataTable dt = new DataTable("NewDt"); //Create a self-growing ID column DataColumn dc = ("ID", ("System.Int32")); = true; //Automatically increase = 1; //The beginning is 1 = 1; //The step size is 1 = false; //Not empty //Create other lists (new DataColumn("Name", (""))); (new DataColumn("Age", ("System.Int32"))); (new DataColumn("Score", (""))); (new DataColumn("CreateTime", (""))); //Create data DataRow dr = (); dr["Name"] = "Zhang San"; dr["Age"] = 28; dr["Score"] = 85.5; dr["CreateTime"] = ; (dr); dr = (); dr["Name"] = "Li Si"; dr["Age"] = 24; dr["Score"] = 72; dr["CreateTime"] = ; (dr); dr = (); dr["Name"] = "Wang Wu"; dr["Age"] = 36; dr["Score"] = 63.5; dr["CreateTime"] = ; (dr); return dt; }
2. Iterate over DataTable objects
/// <summary> /// traverse the DataTable object and convert it into a List object/// </summary> public static List<UserInfo> TraverseDataTable(DataTable dt) { List<UserInfo> userList = new List<UserInfo>(); //Judge whether DataTable is empty if (dt == null || == 0) { return null; } //Transfer the DataTable object and convert it to List foreach (DataRow row in ) { UserInfo user = new UserInfo(); if (("ID") && !(row["ID"])) = Convert.ToInt32(row["ID"]); if (("Name") && !(row["Name"])) = (row["Name"]); if (("Age") && !(row["Age"])) = Convert.ToInt32(row["Age"]); if (("Score") && !(row["Score"])) = (row["Score"]); if (("CreateTime") && !(row["CreateTime"])) = (row["CreateTime"]); (user); } return userList; }
Other codes:
/// <summary> /// User information category/// </summary> public class UserInfo { /// <summary> /// serial number /// </summary> public int ID { get; set; } /// <summary> /// Name /// </summary> public string Name { get; set; } /// <summary> /// age /// </summary> public int Age { get; set; } /// <summary> /// score /// </summary> public double Score { get; set; } /// <summary> /// Creation time /// </summary> public DateTime CreateTime { get; set; } }
This is the end of this article about the creation and traversal implementation of DataTable in C#. For more related C# DataTable creation and traversal content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!