VB.net: 想利用数据绑定过的ComboBox向Access添加记录,选择值后出错
问题描述:
利用form1窗体,获得用户输入的信息,向tblGames中新加记录。
当form1_load后不对cmbPlatform进行操作,只是输入几个文本框内容那么记录能添加到tblGames里面,列3 中的值就是form1_load后显示的第一个成员对应的值XB。
但点开cmbPlatform选了值后,系统就报错:
“System.Data.ConstraintException”类型的未经处理的异常在 System.Data.dll 中发生
其他信息: 列”PFID”被约束为是唯一的。值”PS”已存在。
删不删两个表的关系都没有用
还请帮忙查看哪里出了问题。
非常感谢
HanZhengrong
程序的基本信息如下:
Access: Games.accd
表1: tblGames
列1: GameID (自动编号,此列是主键)
列2: Title (文本,存放游戏标题)
列3: Platform (短文本,此列为外键对应表2的主键)
列4: Rating (文本)
列5: Price (整数)
列6: Quantity (整数)
表2: tblPlatform
列1: PFID (短文本,此列是主键)包含三个值{XB,PS,WII}
列2: Platform(短文本) 包含三个值{Xbox one,Playstation, WII}
关系:
表2的PFID与表1的列3 Platform是一对多关系
窗体控件:
Form: form1
TextBox: txtGameName
ComboBox: cmbPlatform
数据源: TblPlatformBindingSource
显示成员: Platform
'tblPlatform中的列2
值成员: PFID 'tblPlatform中的列1
选定值: TblPlatformBindingSource - PFID
TextBox: txtPrice
TextBox: txtPrice
TextBox: txtQty
Button: btnAdd
代码如下:
Option Explicit On
Option Strict On
Option Infer On
Imports System.Data.OleDb
Public Class Form1
Public strConn As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Games.accdb"
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: 这行代码将数据加载到表“GamesDataSet.tblGames”中。您可以根据需要移动或删除它。
Me.TblGamesTableAdapter.Fill(Me.GamesDataSet.tblGames)
'TODO: 这行代码将数据加载到表“GamesDataSet.tblPlatform”中。您可以根据需要移动或删除它。
Me.TblPlatformTableAdapter.Fill(Me.GamesDataSet.tblPlatform)
End Sub
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
Dim intPrice As Integer = CType(txtPrice.Text, Integer)
Dim intQty As Integer = CType(txtQty.Text, Integer)
Dim strPMID As String = CType(cmbPlatform.SelectedValue, String)
Try
Try
Dim sqlconn As New OleDb.OleDbConnection
Dim sqlquery As New OleDb.OleDbCommand
Dim connString As String
connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Test-Games\Test-Games\Games.accdb;Persist Security Info = False;"
sqlconn.ConnectionString = connString
sqlquery.Connection = sqlconn
sqlconn.Open()
sqlquery.CommandText = "INSERT INTO tblGames([Title], [Platform],[Price],[Quantity])VALUES(@Title, @Platform,@Price,@Quantity)"
sqlquery.Parameters.AddWithValue("@Title", txtGameName.Text)
sqlquery.Parameters.AddWithValue("@Platform", strPMID)
sqlquery.Parameters.AddWithValue("@Price", txtPrice.Text)
sqlquery.Parameters.AddWithValue("@Quantity", txtQty.Text)
sqlquery.ExecuteNonQuery()
sqlconn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Validate()
TblGamesBindingSource.EndEdit()
TblGamesTableAdapter.Update(GamesDataSet.tblGames)
MessageBox.Show("New Record Saved!", "Info. Managerment", MessageBoxButtons.OK)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
End Class