HOW TO:给DataTable添加一自增列至首列

Author:水如烟

 

示例

         Dim  db  As   New  LzmTW.Data.AccessOleDbDatabase( " G:/OfficeNorthwind.mdb " )

        
Dim  cm  As  DbCommand  =  db.CreateCommand( " Employees " )
        cm.Connection.Open()
        
Dim  table  As  DataTable  =  cm.ExecuteReader.GetSchemaTable
        cm.Connection.Dispose()
        cm.Dispose()


        
Dim  nowTable  As  DataTable  =  TableHelper.AddAutoIncreaseColumn(table,  " NO " 1 )

代码:

Public   Class  TableHelper
    
Sub   New ()
    
End Sub

    
Public   Shared   Function  AddAutoIncreaseColumn( ByVal  table  As  DataTable,  ByVal  columnName  As   String Optional   ByVal  seed  As   Integer   =   0 Optional   ByVal  [ step As   Integer   =   1 As  DataTable
        
Dim  autoIncreaseColumn  As   New  DataColumn(columnName,  GetType ( Integer ))
        
With  autoIncreaseColumn
            .AutoIncrement 
=   True
            .AutoIncrementSeed 
=  seed
            .AutoIncrementStep 
=  [ step ]
            .ReadOnly 
=   True
        
End   With

        
Dim  tmpTable  As  DataTable  =  table.Clone
        tmpTable.PrimaryKey = Nothing

        
Dim  result  As   New  DataTable(table.TableName)

        result.Columns.Add(autoIncreaseColumn)

        
Dim  tmpCol  As  DataColumn
        
For   Each  col  As  DataColumn  In  table.Columns
            tmpCol 
=  tmpTable.Columns(col.ColumnName)
            tmpTable.Columns.Remove(tmpCol)
            result.Columns.Add(tmpCol)
        
Next

        result.Merge(table)

        
Return  result
    
End Function
End Class

你可能感兴趣的:(HOW,TO,系列)