小编给大家分享一下C#中如何创建与遍历DataTable对象,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!
1、创建DataTable对象
/// <summary>/// 创建DataTable对象/// </summary>public static DataTable CreateDataTable(){ //创建DataTable DataTable dt = new DataTable("NewDt"); //创建自增长的ID列 DataColumn dc = dt.Columns.Add("ID", Type.GetType("System.Int32")); dc.AutoIncrement = true; //自动增加 dc.AutoIncrementSeed = 1; //起始为1 dc.AutoIncrementStep = 1; //步长为1 dc.AllowDBNull = false; //非空 //创建其它列表 dt.Columns.Add(new DataColumn("Name", Type.GetType("System.String"))); dt.Columns.Add(new DataColumn("Age", Type.GetType("System.Int32"))); dt.Columns.Add(new DataColumn("Score", Type.GetType("System.Decimal"))); dt.Columns.Add(new DataColumn("CreateTime", Type.GetType("System.DateTime"))); //创建数据 DataRow dr = dt.NewRow(); dr["Name"] = "张三"; dr["Age"] = 28; dr["Score"] = 85.5; dr["CreateTime"] = DateTime.Now; dt.Rows.Add(dr); dr = dt.NewRow(); dr["Name"] = "李四"; dr["Age"] = 24; dr["Score"] = 72; dr["CreateTime"] = DateTime.Now; dt.Rows.Add(dr); dr = dt.NewRow(); dr["Name"] = "王五"; dr["Age"] = 36; dr["Score"] = 63.5; dr["CreateTime"] = DateTime.Now; dt.Rows.Add(dr); return dt;}
2、遍历DataTable对象
/// <summary>/// 遍历DataTable对象,转换成List对象/// </summary>public static List<UserInfo> TraverseDataTable(DataTable dt){ List<UserInfo> userList = new List<UserInfo>(); //判断DataTable是否为空 if (dt == null || dt.Rows.Count == 0) { return null; } //遍历DataTable对象,转换成List foreach (DataRow row in dt.Rows) { UserInfo user = new UserInfo(); if (dt.Columns.Contains("ID") && !Convert.IsDBNull(row["ID"])) user.ID = Convert.ToInt32(row["ID"]); if (dt.Columns.Contains("Name") && !Convert.IsDBNull(row["Name"])) user.Name = Convert.ToString(row["Name"]); if (dt.Columns.Contains("Age") && !Convert.IsDBNull(row["Age"])) user.Age = Convert.ToInt32(row["Age"]); if (dt.Columns.Contains("Score") && !Convert.IsDBNull(row["Score"])) user.Score = Convert.ToDouble(row["Score"]); if (dt.Columns.Contains("CreateTime") && !Convert.IsDBNull(row["CreateTime"])) user.CreateTime = Convert.ToDateTime(row["CreateTime"]); userList.Add(user); } return userList;}
其它代码:
/// <summary>/// 用户信息类/// </summary>public class UserInfo{ /// <summary> /// 编号 /// </summary> public int ID { get; set; } /// <summary> /// 名称 /// </summary> public string Name { get; set; } /// <summary> /// 年龄 /// </summary> public int Age { get; set; } /// <summary> /// 成绩 /// </summary> public double Score { get; set; } /// <summary> /// 创建时间 /// </summary> public DateTime CreateTime { get; set; }}
以上是“C#中如何创建与遍历DataTable对象”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注编程网行业资讯频道!