There are times when you may need to create a DataTable to fill on the fly which requires a auto incrementing primary key. To make life simple I created several language extensions.
The first creates one with the field name of Identifier
Next, provides a parameter to supply the column nameCode:AddPrimaryKey(ByVal sender As DataColumnCollection)
Supply column name and seedCode:AddPrimaryKey(ByVal sender As DataColumnCollection, ByVal ColumnName As String)
Lastly supply column name, seed and stepCode:Public Sub AddPrimaryKey(ByVal sender As DataColumnCollection, _ ByVal ColumnName As String, ByVal Seed As Integer)
Example usageCode:Public Sub AddPrimaryKey(ByVal sender As DataColumnCollection, _ ByVal ColumnName As String, ByVal Seed As Integer, _ ByVal StepAmount As Integer)
Code:Sub Main() Dim Table1 As New DataTable Table1.Columns.AddPrimaryKey("ID", 10, 20) Table1.Columns.Add(New DataColumn("LastName", _ GetType(System.String))) Table1.Rows.Add(New Object() {Nothing, "Gallagher"}) Table1.Rows.Add(New Object() {Nothing, "Smith"}) Table1.Rows.Add(New Object() {Nothing, "Jones"}) Console.WriteLine("Example 1: AddPrimaryKey(""ID"", 10, 20)") For Each Row As DataRow In Table1.Rows Console.WriteLine("ID={0} Last Name {1}", _ Row("ID"), _ Row("LastName")) Next Console.WriteLine() Console.WriteLine("Example 2: AddPrimaryKey()") Dim Table2 As New DataTable Table2.Columns.AddPrimaryKey() Table2.Columns.Add(New DataColumn("LastName", _ GetType(System.String))) Table2.Rows.Add(New Object() {Nothing, "Smith"}) Table2.Rows.Add(New Object() {Nothing, "Gallagher"}) Table2.Rows.Add(New Object() {Nothing, "Jones"}) For Each Row As DataRow In Table2.Rows Console.WriteLine("ID={0} Last Name {1}", _ Row("Identifier"), _ Row("LastName")) Next Console.WriteLine() Console.ReadLine() End Sub


Reply With Quote