Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleCreate a unique constraint on data in VB.NET
KeywordsVB.NET, NET, DataGrid, ADO.NET, unique, constraint
CategoriesDatabase, VB.NET
 
Create a new DataSet. Add a new DataTable to the DataSet. Define the DataTable's columns.

Then make an array of DataColumn objects, one for each column involved in the constraint. Save references to the DataSet's columns in this array. Then use the array to create a new UniqueConstraint object.

Now populate the DataTable and bind the table to a DataGrid. The user will be unable to add new records to the DataGrid that violate the uniqueness constraint.

 
Private m_DataSet As DataSet
Private m_dtPeople As DataTable

' Create some data and bind it to the DataGrid.
Private Sub Form1_Load(ByVal sender As System.Object, ByVal _
    e As System.EventArgs) Handles MyBase.Load
    ' Build the DataSet.
    m_DataSet = New DataSet()

    ' Build the People table.
    m_dtPeople = New DataTable("People")
    m_DataSet.Tables.Add(m_dtPeople)
    m_dtPeople.Columns.Add("LastName", GetType(String))
    m_dtPeople.Columns.Add("FirstName", GetType(String))
    m_dtPeople.Columns.Add("Email", GetType(String))

    ' Make the UniqueConstraint on LastName
    ' and FirstName.
    Dim data_columns(1) As DataColumn
    Dim unique_constraint As UniqueConstraint

    data_columns(0) = m_dtPeople.Columns("LastName")
    data_columns(1) = m_dtPeople.Columns("FirstName")
    unique_constraint = New UniqueConstraint(data_columns)
    m_dtPeople.Constraints.Add(unique_constraint)

    ' Populate the People table.
    Dim people_data(2) As String
    people_data(0) = "Jennie"
    people_data(1) = "Simpson"
    people_data(2) = "JennieSimpson@dev.null.com"
    m_dtPeople.Rows.Add(people_data)

    people_data(0) = "Nik"
    people_data(1) = "Oswald"
    people_data(2) = "Nik@SomewhereElse.com"
    m_dtPeople.Rows.Add(people_data)

    ' Add other records ...

    ' Bind the DataGrid to the DataTable.
    dgPeople.DataSource = m_dtPeople
End Sub
 
For more information on using databases in Visual Basic .NET, see my book Visual Basic .NET Database Programming.
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated