Datatable添加数据,提示该行已经属于另一个表的解决方法

来源:互联网 发布:caro emerald知乎 编辑:程序博客网 时间:2024/05/16 12:54

一、DataTable.Rows.Add(DataRow.ItemArray);

二、DataTable.ImportRow(DataRow)

三、设置DataTable的tablename,然后.Rows.Add

第一种方法在项目中用到,确实好用!不过感觉第二种应该更好用一些.


案例

DataTable newDt = new DataTable();
                newDt.Columns.Add("id", typeof(string));
                newDt.Columns.Add("name", typeof(string));
                newDt.Columns.Add("url", typeof(string));
                newDt.Columns.Add("description", typeof(string));
                newDt.Columns.Add("parentid", typeof(string));
                newDt.Columns.Add("icon", typeof(string));
                newDt.Columns.Add("sortIndex", typeof(int));
                 
                DataRow drr = newDt.NewRow(); 
                DataRow dr = newDt.NewRow();

//父节点-表

                string sql = "select * from tb_APPMenu where parentID ='' order by sortindex asc";
                DataTable dt = helper.GetDataTable(sql); 
//子节点-表(parentID=父表-ID)
                string sqlparent = "select * from tb_APPMenu where parentID !='' order by sortindex asc";
                DataTable dtparent = helper.GetDataTable(sqlparent);
                //父节点
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    //主菜单
                    drr = newDt.NewRow();
                    drr["id"] = dt.Rows[i]["id"].ToString();
                    drr["name"] = dt.Rows[i]["name"].ToString();
                    drr["url"] = dt.Rows[i]["url"].ToString();
                    drr["description"] = dt.Rows[i]["description"].ToString();
                    drr["parentid"] = dt.Rows[i]["parentid"].ToString();
                    drr["icon"] = dt.Rows[i]["icon"].ToString();
                    drr["sortIndex"] = dt.Rows[i]["sortIndex"];
                    newDt.Rows.Add(drr);


                    //子菜单
                    foreach (DataRow drt in dtparent.Rows)
                    { 
                        if (dt.Rows[i]["id"].ToString() == drt["parentid"].ToString())
                        {
                            //--死办法--
                            //dr = newDt.NewRow();
                            //dr["id"] = drt["id"].ToString();
                            //dr["name"] = drt["name"].ToString();
                            //dr["url"] = drt["url"].ToString();
                            //dr["description"] = drt["description"].ToString();
                            //dr["parentid"] = drt["parentid"].ToString();
                            //dr["icon"] = drt["icon"].ToString();
                            //dr["sortIndex"] = drt["sortIndex"];
                            //newDt.Rows.Add(dr);  

                            //该行已经属于另一个表的解决方法 

   //方法一

   newDt.Rows.Add(drt.ItemArray);

                            // 方法二
                            newDt.ImportRow(drt);
                        }
                    }  
                }   

阅读全文
0 0