DataTable加上编号,截取列

 
刚刚碰到对DataTable的操作,记录一下两个方法,或许对你有用
 
/// <summary>
/// 给已有DataTable的首列加上序号列
/// </summary>
/// <param name="srcTable">源数据表</param>
/// <returns>结果数据表</returns>
private DataTable GetDataTable(DataTable srcTable)
{
    DataTable dstntnTable = new DataTable();
    dstntnTable.Columns.Add("Id", typeof(Int32));
    for (int i = 0; i < srcTable.Columns.Count; i++)
        dstntnTable.Columns.Add(srcTable.Columns[i].ColumnName, srcTable.Columns[i].DataType);
    int srcColCount = srcTable.Columns.Count;
    int srcRowCount = srcTable.Rows.Count;
    int dstntnRowCount = 0;
    for (int j = 0; j < srcRowCount; j++)
    {
        DataRow newRow = dstntnTable.NewRow();
        newRow[0] = (++dstntnRowCount);
        for (int k = 0; k < srcColCount; k++)
            newRow[k + 1] = srcTable.Rows[j][k];
        dstntnTable.Rows.Add(newRow);
    }
    return dstntnTable;
}
 
/// <summary>
/// 取出指定数据表中指定列数据并在首列加上编号列
/// </summary>
/// <param name="srcTable">源数据表</param>
/// <param name="para">需要取出源数据表的列名</param>
/// <returns>结果数据表</returns>
private DataTable GetDataTable(DataTable srcTable, params string[] para)
{
    DataTable dstntnTable = new DataTable();
    dstntnTable.Columns.Add("Id", typeof(Int32));
    for (int i = 0; i < para.Length; i++)
        dstntnTable.Columns.Add(para[i], srcTable.Columns[para[i]].DataType);
    int srcRowCount = srcTable.Rows.Count;
    int dstntnRowCount = 0;
    for (int j = 0; j < srcRowCount; j++)
    {
        DataRow newRow = dstntnTable.NewRow();
        newRow["Id"] = (++dstntnRowCount);
        for (int k = 0; k < para.Length; k++)
            newRow[para[k]] = srcTable.Rows[j][para[k]];
        dstntnTable.Rows.Add(newRow);
    }
    return dstntnTable;
}
posted @ 2009-02-18 15:55  Simens  阅读(1253)  评论(4编辑  收藏  举报