【问题标题】:Table doesn't have a primary key idpdf表没有主键 idpdf
【发布时间】:2019-05-23 21:33:22
【问题描述】:

为什么会出现这个错误

表没有主键。

虽然我在创建表 (pdfinfo) 期间将 (idpdf) 设为主要

在这一行

Dim row As DataRow = dt.Rows.Find(ComboBox1.SelectedValue)

 Private Sub mylib_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load


    adapter = New SqlDataAdapter("select * from pdfinfo ", connection)
    adapter.Fill(dt)

    ComboBox1.DataSource = dt
    ComboBox1.DisplayMember = "pdfname"
    ComboBox1.ValueMember = "idpdf"

    dt.Constraints.Add("Primary", dt.Columns("idpdf"), True)


End Sub

Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged

    Dim filename As String = ComboBox1.Text
    Dim row As DataRow = dt.Rows.Find(ComboBox1.SelectedValue)
    Dim file_data() As Byte = CType(row(2), Byte())
    Dim fs As New FileStream(filename, FileMode.OpenOrCreate, FileAccess.Write)

    fs.Write(file_data, 0, file_data.Length)
    fs.Close()

    Process.Start(filename)

End Sub

【问题讨论】:

  • 在将dt分配给组合框之前尝试设置主键约束。
  • 假设您的数据库表有一个主键,将您的数据适配器的MissingSchemaAction 设置为AddWithKey。然后调用Fill 将自动设置PrimaryKeyDataTable
  • 也就是说,在这种情况下调用Find 有什么意义呢?只需使用DirectCast(ComboBox1.SelectedItem, DataRowView).Row 即可获得DataRow。事实上,您甚至不需要DataRow,因为您从SelectedItem 获得的DataRowView 无论如何都可以为您提供字段数据。
  • @jmcilhinney 谢谢这个“ DirectCast(ComboBox1.SelectedItem, DataRowView).Row ”解决了我的问题

标签: sql-server vb.net


【解决方案1】:

要定义表的主键,您应该使用PrimaryKey 属性,而不是用于外键或唯一约束的Constraints

dt.PrimaryKey = New DataColumn() {dt.Columns("idpdf"))

【讨论】:

  • @HazimMohammed : 如果史蒂夫的回答解决了您的问题,请按他帖子左侧的勾选/复选标记将其标记为已接受 .有关其工作原理的更多信息,请参阅:How does accepting an answer work?
猜你喜欢
  • 2011-04-03
  • 2013-07-27
  • 1970-01-01
  • 2023-03-11
  • 1970-01-01
  • 1970-01-01
  • 2012-02-14
  • 2013-05-09
  • 1970-01-01
相关资源
最近更新 更多