2010-03-18 86 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