vb.net DataSet, DataAdapter, 无 dataTable 主键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19032845/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 15:15:07  来源:igfitidea点击:

DataSet, DataAdapter, no dataTable Primary key

vb.netoledb

提问by Mokmeuh

Ok so I'm having this:

好的,所以我有这个:

Dim sql As String = "SELECT * FROM Articles"
dAdapter = New OleDbDataAdapter(sql, connection)
dSet = New DataSet("tempDatatable")

With connection
    .Open()
    dAdapter.Fill(dSet, "Articles_table")
    .Close()
End With

With DataGridView1
    .DataSource = dSet
    .DataMember = "Articles_table"
End With

And I wonder if there is any possible way to define the first column as the primary key. I've looked around but everyone is using a manual datatable to fill up the datagrid. Since I'm using a dataBase I don't know how to set a primary key from there. I need some help.

我想知道是否有任何可能的方法将第一列定义为主键。我环顾四周,但每个人都在使用手动数据表来填充数据网格。由于我使用的是数据库,因此我不知道如何从那里设置主键。我需要帮助。

回答by Tim Schmelter

You have to set the DataAdapter's MissingSchemaActionto AddWithKey:

您必须将DataAdapter's设置MissingSchemaActionAddWithKey

var table = new DataTable();
using(var con = new SqlConnection(connectionString))
using (var da = new SqlDataAdapter("SELECT * FROM Articles", con))
{
    da.MissingSchemaAction = MissingSchemaAction.AddWithKey
    da.Fill(table);
}

Edit: VB.NET:

编辑:VB.NET:

Dim table = New DataTable()
Using con = New SqlConnection(connectionString)
    Using da = New SqlDataAdapter("SELECT * FROM Articles", con)
        da.MissingSchemaAction = MissingSchemaAction.AddWithKey
        da.Fill(table)
    End Using
End Using

Now the necessary columns and primary key information to complete the schema are automaticaly added to the DataTable.

现在,完成架构所需的列和主键信息会自动添加到DataTable.

Read: Populating a DataSet from a DataAdapter

阅读:从 DataAdapter 填充 DataSet

回答by GarethD

You can add a primary key to your data table using something like this:

您可以使用如下方式向数据表添加主键:

var table = dSet.Tables["Articles_table"];
table.PrimaryKey = new DataColumn[] { table.Columns[0] };

Sorry, just realised the question was tagged with vb.net, not c#. VB.net would be:

抱歉,刚刚意识到问题被标记为 vb.net,而不是 c#。VB.net 将是:

Dim table = dSet.Tables("Articles_table")
table.PrimaryKey = New DataColumn() {table.Columns(0)}

回答by user981849

Please do it like this.

请这样做。

Dim objTmpTable As New DataTable
   objTmpTable.PrimaryKey = New DataColumn() {objTmpTable.Columns(0)}
   dgrdMeasure.DataSource = objTmpTable
   dgrdMeasure.DataBind()

That is, before assigning to Grid, just set the Primary key.

也就是说,在分配给 Grid 之前,只需设置主键。