使用标识主键将新记录添加到表中

时间:2013-03-23 00:21:10

标签: vb.net

我的数据库中有这个表结构:

CREATE TABLE RIAD (
NumeroR int primary key identity,
 NomR varchar(50),
 AdresseRueR varchar(50),
 CodePostalR int,
  VilleR varchar(50),
 TelephoneR varchar(50),
 NomContactR varchar(50),
 CodeReg int,
 NombreDePlaces int)

我有这样的表格:

enter image description here

我想点击按钮Ajouter,将新记录从三个按钮上方的文本字段添加到我的数据库中的RIAD表中。

这是我尝试过的代码:

Public cnx As New SqlConnection("data source=localhost; initial catalog=EFF_TSDI_2009_V1; integrated security=sspi")
    Public ds As New DataSet
    Public adapterRiad As SqlDataAdapter
    Public builderRiad As SqlCommandBuilder

Private Sub MajRiad_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        adapterRiad = New SqlDataAdapter()
        adapterRiad.SelectCommand = New SqlCommand("SELECT  * FROM RIAD", cnx)
        adapterRiad.Fill(ds, "RIAD")
        DataGridView1.DataSource = ds.Tables("RIAD")
        builderRiad = New SqlCommandBuilder(adapterRiad)
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim dialog As DialogResult = MessageBox.Show("Voulez vous vraiment ajouter cette personne ?", "Confirmation", MessageBoxButtons.YesNo)
        If (dialog = DialogResult.Yes) Then

            ds.Tables("RIAD").Rows.Add(nomR.Text, AdresseRueR.Text, CInt(CodePostalR.Text), VilleR.Text, TelephoneR.Text, NomContactR.Text, _
CInt(CodeReg.Text), CInt(NombreDePlaces.Text))
            For Each c As Control In Me.Controls
                If TypeOf (c) Is TextBox Then
                    c.Text = String.Empty
                End If
            Next
            adapterRiad.InsertCommand = builderRiad.GetInsertCommand
            adapterRiad.Update(ds, "RIAD")

        End If
    End Sub

但是当我点击按钮Ajouter时,我收到了这个错误:

  

输入字符串的格式不正确。不能存储在NumeroR列中。预期类型为Int32。

<eeeee>是我试图在NomR文本字段中写入的值,VB.net正在尝试使用NomR文本字段的值保存新行作为主键,但主键是标识

1 个答案:

答案 0 :(得分:0)

您可能希望明确说明哪个字段位于哪里,而不是使用Rows.Add()方法...这是更多代码,但会阻止框架代表您做出假设。

Here是一个参考。相关部分是“将新记录插入无类型数据集”

所以你可以这样做:

Dim newRiadRow As DataRow = ds.Tables("RIAD").NewRow()

newCustomersRow("NomR") = nomR.Text
newCustomersRow("AdresseRueR") = AdresseRueR.Text
'More fields here

ds.Tables("RIAD").Rows.Add(newRiadRow)