Thursday, June 19, 2008

How to check Column is Primary Key Column in DataTable

This article explains how to check a Column of DataTable whether it is a Primary Key column or NOT in a Un-Typed DataSet or Typed DataSet. Also we will discuss how to get the Primary Key columns of a DataTable.

Level: Beginner

Knowledge Required:
  • Typed DataSet / Un-Typed DataSet
  • DataTable
  • Primary Key
Description:
To check a column whether it is a Primary Key or NOT use the following function:

Private Function IsPrimaryKeyColumn(ByRef Table As DataTable, ByRef Column As DataColumn) As Boolean
Return Array.IndexOf(Table.PrimaryKey, Column) >= 0
End Function

DataTable exposes a property PrimaryKey() which is actually array of DataColumn, since a Primary Key can also be a composite key (key composed with more than one columns) that is why it is an Array. So we just search the given column in that array, if found then it means this column is a Primary Key.

Usage Typed DataSet:

Dim b As Boolean
b = IsPrimaryKeyColumn(OrderDataSet.Order, OrderDataSet.Order.Order_IDColumn)

Usage Un-Typed DataSet:

Dim b As Boolean
b = IsPrimaryKeyColumn(DS.Tables("Order"), DS.Tables("Order").Columns("Order_IDColumn"))

No comments: