【发布时间】: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将自动设置PrimaryKey的DataTable。 -
也就是说,在这种情况下调用
Find有什么意义呢?只需使用DirectCast(ComboBox1.SelectedItem, DataRowView).Row即可获得DataRow。事实上,您甚至不需要DataRow,因为您从SelectedItem获得的DataRowView无论如何都可以为您提供字段数据。 -
@jmcilhinney 谢谢这个“ DirectCast(ComboBox1.SelectedItem, DataRowView).Row ”解决了我的问题
标签: sql-server vb.net