2013-03-23 29 views
0

我在我的數據庫有此表結構:添加新的記錄入表中標識的主鍵

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我得到這個錯誤:

輸入字符串的不正確的format.Couldn't存儲在NumeroR列中。預期的類型是Int32。

<eeeee>是我試圖在NomR文本字段寫入值,和VB.net試圖保存新行作爲主鍵NomR文本字段的值,但主鍵是身份。

回答

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) 
相關問題