DataTable的新建、查询、添加和修改

详细讲解了C#开发中数据类型DataTable的使用,包括新建DataTable,查询DataTable,在DataTable里添加记录,添加 列,修改列的属性以及修改某行某列的值的方法。同时说明了将DataTable作为LoopUpEdit控件的数据源时的注意点。

string userid = "UserID = {0}";             //查找初审人,流程阶段为初审,权限类型为受理             IList list_InitAudUser = ManagerFactory.GetS_UserAcce_FlowManager().SearchUsers(p_ywtype, 10100002, 10110001);

//新建DataTable,包含两列,并对它进行赋值             DataTable table_InitAudUser = new DataTable();             table_InitAudUser.Columns.Add("UserID", typeof(int));             table_InitAudUser.Columns.Add("RealName", typeof(string));             DataRow row_InitAudUser = null;            for (int i = 0; i < list_InitAudUser.Count; i++)             {                 row_InitAudUser = table_InitAudUser.NewRow();                 S_UserAcce_Flow s_UserAcce_Flow = list_InitAudUser[i] as Model.S_UserAcce_Flow;                 row_InitAudUser["UserID"] = s_UserAcce_Flow.USERID;                 //对USERID进行翻译                 row_InitAudUser["RealName"] = ManagerFactory.GetS_USERManager().GetRealNameByID(s_UserAcce_Flow.USERID);                 table_InitAudUser.Rows.Add(row_InitAudUser);             }

//查询,查不到则添加             DataRow[] scr_row = table_InitAudUser.Select(string.Format(userid, scr));             if (scr_row.Length == 0)             {                 row_InitAudUser = table_InitAudUser.NewRow();                 row_InitAudUser["UserID"] = scr;                 row_InitAudUser["RealName"] = ManagerFactory.GetS_USERManager().GetRealNameByID(scr);                 table_InitAudUser.Rows.Add(row_InitAudUser);             }

//将DataTable作为LookUpEdit控件的数据源,注意将控件的列的属性和DataTable里列的属性一一对应             this.lookUpEdit_IniAudPer.Properties.ValueMember = "UserID";             this.lookUpEdit_IniAudPer.Properties.DisplayMember = "RealName";             this.lookUpEdit_IniAudPer.Properties.DataSource = table_InitAudUser;

附:1、修改DataTable里列的属性:先得到该列,再修改其属性,如下: table_InitAudUser.Columns["UserID"].DataType=Type.GetType("System.bool");

2、修改某行某列的值:

for (int i = 0; i < table_InitAudUser.Rows.Count; i++)

table_InitAudUser.Rows[i]["RealName"] = "泽泽";

上一篇:如何连接OracleRAC


下一篇:PAT1059:Prime Factors