2010-03-18 68 views

回答

5

您可以設定一個表的主鍵:

Dim table As New DataTable() 

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

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

爲了能夠使用主鍵,您需要確保在給定的列中的所有值都是唯一的。

我主要是在C#中工作,有一對夫婦的擴展方法我用我需要讓「整潔」的叫聲,你可能要考慮轉換到VB和使用:

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"); 
9

只要在列中的值是唯一的

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

調整爲列名。

9

這裏VB中的一行代碼(問題在於「使用VB.NET」)。這個例子是2列索引:

table.PrimaryKey = New DataColumn() {table.Columns("column1"), _ 
            table.Columns("column2")} 

更新:下面是關於如何使用這個2列索引來查找行另外一個班輪:

table.Rows.Find(New Object() {value1, value2}) '<- DataRow returned 
1

感謝您的回答羅布 - vb版本存在一個小問題,儘管索引應該爲零:

Dim table As New DataTable() 

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

Dim primaryKey(1) As DataColumn 
primaryKey(0) = table.Columns("MyColumn") 
table.PrimaryKey = primaryKey 
相關問題