如何在数据库中从gridview插入多行

时间:2014-10-30 08:46:53

标签: vb.net-2010

Protected Sub btnSave_Click(sender As Object, e As EventArgs)
    Dim invoiceclass As New InvoiceClass()
    Dim invoicedb As New DbInvoiceClass()
    invoiceclass.CustomerName = txtCustomerName.Text
    invoiceclass.DateInvoice = txtDate.Text
    invoiceclass.NetTotal = txtNetTotal.Text
    invoicedb.InsertInvoice(invoiceclass)
    Dim ID As Integer


    Dim con As New SqlConnection(DbConnectionClass.ConnectionStringName)


    con.Open()
    If con.State = System.Data.ConnectionState.Open Then

        Dim comm As New SqlCommand("SELECT MAX(Code) FROM InvoiceTB", con)
        comm.ExecuteNonQuery()

        ID = Convert.ToInt32(comm.ExecuteScalar())


        For Each item As GridViewRow In gvrview.Rows

            'Modified according your table Definition 
            Dim statment As String = String.Format("insert into  InvoiceItem ( ProductName,Price, Quantity, Total,CodeInvoice ) values ('{0}',{1},{2},{3},{4} )", item.Cells(1).Text, item.Cells(2).Text, item.Cells(3).Text, ID.ToString())
            Dim cmd As New SqlCommand(statment, con)

            cmd.CommandType = CommandType.Text
            cmd.ExecuteNonQuery()
            con.Close()

            cmd.Dispose()
        Next




    End If
    con.Close()


End Sub

它给了我这个错误....索引(从零开始)必须大于或等于零且小于参数列表的大小。

1 个答案:

答案 0 :(得分:0)

我的猜测是你从单元格索引1开始,它实际上是gridview的第二列。

Column2 = item.Cells(1).Text
Column3 = item.Cells(2).Text
Column4 = item.Cells(3).Text

如果你没有column4并且你试图返回item.Cells(3).Text,你将获得例外。

如果我的假设是正确的,并且你的网格视图中只有3列,那么用这一行替换该行,你将全部设置。

Dim statment As String = String.Format("insert into  InvoiceItem ( ProductName,Price, Quantity, Total,CodeInvoice ) values ('{0}',{1},{2},{3},{4} )", item.Cells(0).Text, item.Cells(1).Text, item.Cells(2).Text, ID.ToString())