由dataview生成对应的datatable的方法

 /// <summary>
    /// 由dataview生成对应的datatable
    /// </summary>
    /// <param name="obDataView"></param>
    /// <returns></returns>
    public static DataTable CreateTable(DataView obDataView)
    {
        if (null == obDataView)
        {
            throw new ArgumentNullException("DataView", "Invalid DataView object specified");
        }
        DataTable obNewDt = obDataView.Table.Clone();
        int idx = 0;
        string[] strColNames = new string[obNewDt.Columns.Count];
        foreach (DataColumn col in obNewDt.Columns)
        {
            strColNames[idx++] = col.ColumnName;
        }
        IEnumerator viewEnumerator = obDataView.GetEnumerator();
        while (viewEnumerator.MoveNext())
        {
            DataRowView drv = (DataRowView)viewEnumerator.Current;
            DataRow dr = obNewDt.NewRow();
            try
            {
                foreach (string strName in strColNames)
                {
                    dr[strName] = drv[strName];
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            obNewDt.Rows.Add(dr);
        }
        return obNewDt;
    }

下面是编的一个小例子,用来将指定index所取集合范围的原表(dt)记录组合到另一个新表(dtNew)中,将新表返回:

DataTable dtNew = dt.Clone();
        DataView dv = dt.DefaultView;
        foreach (string index in lst)
        {
            dv.RowFilter = "id=" + index;
            DataTable dataTemp = CreateTable(dv);
            DataRow dr = dtNew.NewRow();
            for (int i = 0; i < dataTemp.Columns.Count; i++)
            {
                dr[i] = dataTemp.Rows[0][i];
            }

            dtNew.Rows.Add(dr);
        }
      
        return dtNew;


 

 


 

你可能感兴趣的:(由dataview生成对应的datatable的方法)