C#中DataTable的创建与遍历实现

1、创建DataTable对象

/// 
/// 创建DataTable对象
/// 
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对象

/// 
/// 遍历DataTable对象,转换成List对象
/// 
public static List TraverseDataTable(DataTable dt)
{
  List userList = new List();
 
  //判断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;
}

其它代码:

/// 
/// 用户信息类
/// 
public class UserInfo
{
  /// 
  /// 编号
  /// 
  public int ID { get; set; }
 
  /// 
  /// 名称
  /// 
  public string Name { get; set; }
 
  /// 
  /// 年龄
  /// 
  public int Age { get; set; }
 
  /// 
  /// 成绩
  /// 
  public double Score { get; set; }
 
  /// 
  /// 创建时间
  /// 
  public DateTime CreateTime { get; set; }
}

到此这篇关于C#中DataTable的创建与遍历实现的文章就介绍到这了,更多相关C# DataTable创建与遍历内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

你可能感兴趣的:(C#中DataTable的创建与遍历实现)