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
DataSet, DataAdapter, no dataTable Primary key
提问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设置MissingSchemaAction为AddWithKey:
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.
回答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 之前,只需设置主键。

