Datatable添加數據,提示該行已經屬於另一個表的解決方法

一、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);
                        }
                    }  
                }   

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章