Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a VB.NET DataTable Column as primary key after creation

I am importing Tables from a Oracle DataBase, using a VB.NET dataAdapter. I use the "fill" command to add the imported data to a DataSet. How is it possible to define a specific column of a DataTable as PrimaryKey, after the DataTable is already filled with data?

like image 660
Olga Avatar asked Mar 18 '10 14:03

Olga


2 Answers

You can set the primary key of a table by:

    Dim table As New DataTable()

    table.Columns.Add(New DataColumn("MyColumn"))

    Dim primaryKey(1) As DataColumn
    primaryKey(1) = table.Columns("MyColumn")
    table.PrimaryKey = primaryKey

To be able to use the primary key, you need to ensure that all values for the given column are unique.

I primarily work in C# and have a couple of Extension methods I use to "tidy" the calls I need to make, which you might want to consider translating to VB and using:

    public static void SetPrimaryKey(this DataTable value, string columnName)
    {
        value.PrimaryKey = new DataColumn[] { value.Columns[columnName] };
    }

    public static DataRow FindByPrimaryKey(this DataTable value, object key)
    {
        return value.Rows.Find(key);
    }

    // I can then do:

    DataTable table = CallToRoutineThatGetsMyDataTable();
    table.SetPrimaryKey("PKColumnName");
    DataRow result = table.FindByPrimaryKey("valueToFindWith");
like image 105
Rob Avatar answered Oct 08 '22 19:10

Rob


As long as the values in the column are unique

table.PrimaryKey = new DataColumn[] { table.Columns["Id"] };

adjust for your column names.

like image 20
Kleinux Avatar answered Oct 08 '22 20:10

Kleinux