在普通情况下,我们使用SqlDataAdapter来Fill填充DataTable,如果使用下列代码我们是不能拿到主键列的:

dataadapter.Fill(Table);
DataColumn[] cols;
cols = Table.PrimaryKey;
for(int i = 0; i < cols.Length; i++)
{
        MessageBox.Show(cols[i].ColumnName);
}

因为数据库中的主键约束在普通情况下是不会设置到DataTable中去的。

解决方法:我们可以加入一句代码,让主键约束设置到DataTable中

代码:

dataadapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
dataadapter.Fill(Table);
DataColumn[] cols;
cols = Table.PrimaryKey;
for(int i = 0; i < cols.Length; i++)
{
        MessageBox.Show(cols[i].ColumnName);
}

相关文章:

  • 2022-12-23
  • 2021-05-24
  • 2022-12-23
  • 2022-12-23
  • 2021-11-18
  • 2022-02-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-10-21
  • 2022-12-23
  • 2021-07-05
  • 2021-11-27
相关资源
相似解决方案