将datagrid值插入SQL Server表

时间:2016-10-27 07:48:39

标签: sql-server vb.net datagridview datagrid

我正在尝试将一些运行时生成的datagridview值插入到SQL Server表中。

这是我的代码:

Private Sub btnTrimitebon_Click(sender As Object, e As EventArgs) Handles btnTrimitebon.Click
    functii.adaugabonmagazie()
    Dim dvgPieseCumparate As New DataGridView
    Dim command As New Data.SqlClient.SqlCommand
    Dim con As New Data.SqlClient.SqlConnection
    Dim dt As DataTable = functii.piesecumparate(txtFpo.Text)
    dvgPieseCumparate.AutoGenerateColumns = True
    dvgPieseCumparate.AllowUserToAddRows = False
    dvgPieseCumparate.AllowUserToDeleteRows = False
    dvgPieseCumparate.AllowUserToOrderColumns = False
    dvgPieseCumparate.AutoSizeColumnsMode =
        DataGridViewAutoSizeColumnsMode.AllCells
    dvgPieseCumparate.DataSource = dt
    dvgPieseCumparate.Refresh()
    Try
        con.ConnectionString = "Data Source=SVNAV;Initial Catalog=NAV_Vermorel_Live;User ID=sa;Password=1234"
        command.CommandText = "INSERT INTO [dbo].[SC Vermorel SRL$MagLines]
          ([RPO]
          ,[FPO]
          ,[Articol]
          ,[Description]
          ,[QtyperPiesa]
          ,[QtyTotal]
          ,[Indice])
    VALUES
          (@RPO
          ,@FPO
          ,@Articol
          ,@Description,
          ,@QtyperPiesa
          ,@QtyTotal
          ,@Indice)"
        command.Parameters.Add("@RPO", SqlDbType.VarChar)
        command.Parameters.Add("@FPO", SqlDbType.VarChar)
        command.Parameters.Add("@Articol", SqlDbType.VarChar)
        command.Parameters.Add("@Description", SqlDbType.VarChar)
        command.Parameters.Add("@QtyperPiesa", SqlDbType.Int)
        command.Parameters.Add("@QtyTotal", SqlDbType.Int)
        command.Parameters.Add("@Indice", SqlDbType.VarChar)
        con.Open()
        command.Connection = con
        For i As Integer = 0 To dvgPieseCumparate.Rows.Count - 1
            command.Parameters(0).Value = dvgPieseCumparate.Rows(i).Cells(0).Value
            command.Parameters(1).Value = dvgPieseCumparate.Rows(i).Cells(1).Value
            command.Parameters(2).Value = dvgPieseCumparate.Rows(i).Cells(2).Value
            command.Parameters(3).Value = dvgPieseCumparate.Rows(i).Cells(3).Value
            command.Parameters(4).Value = dvgPieseCumparate.Rows(i).Cells(4).Value
            command.Parameters(5).Value = dvgPieseCumparate.Rows(i).Cells(5).Value
            command.Parameters(6).Value = dvgPieseCumparate.Rows(i).Cells(6).Value
            command.ExecuteNonQuery()
        Next
    Catch ex As Exception
        Console.WriteLine(ex.Message)
    Finally
        If con IsNot Nothing Then
            If con.State = ConnectionState.Open Then
                con.Close()
            End If
            con.Dispose()
        End If
    End Try
End Sub

SSMS的表定义:

table definition

如果我生成了dgv并将其放在表单上并将其显示为ok,但是当我尝试在sql表中添加其值时,没有错误,但也没有添加任何值。

datagridview

我做错了什么?

0 个答案:

没有答案