2014-10-30 68 views
0
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 

它給了我這個錯誤....索引(基於零)必須大於或等於零並小於參數列表的大小。如何在數據庫中插入gridview中的多行

回答

0

我的猜測是,你從單元索引1開始,這實際上是你的gridview的第二列。

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

如果沒有column4和你試圖返回item.Cells(3)。文本,你會得到一個異常。

如果我的假設是正確的,並且您的gridview中只有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()) 
相關問題