Monday, March 19, 2012

Help! How to insert multiple rows into Database??

I keep getting this error but it will only insert the 1st row into my database table

The variable name '@.CustId' has already been declared. Variable names must be unique within a query batch or stored procedure.

Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs)

Dim drow As GridViewRow

For Each drow In GridView1.Rows

Dim textBoxText As String = CType(drow.FindControl("Label2"), Label).Text

SqlDataSource2.InsertParameters.Add("CustId", TypeCode.String, Profile.UserName)

SqlDataSource2.InsertParameters.Add("OrderDate", TypeCode.DateTime, DateTime.Now.ToString)

SqlDataSource2.InsertParameters.Add("Total", TypeCode.Double, TotalUnitPrice)

SqlDataSource2.InsertParameters.Add("Quantity", TypeCode.Int32, textBoxText)

SqlDataSource2.Insert()

Next

Response.Redirect("checkout.aspx")

End Sub

since you are operating in a loop, you should clear your parameters collection on each pass through

Dim drowAs GridViewRowFor Each drowIn GridView1.RowsDim textBoxTextAs String =CType(drow.FindControl("Label2"), Label).Text SqlDataSource2.InsertParameters.Clear()'<-- Clear the params first SqlDataSource2.InsertParameters.Add("CustId", TypeCode.String, Profile.UserName) SqlDataSource2.InsertParameters.Add("OrderDate", TypeCode.DateTime, DateTime.Now.ToString) SqlDataSource2.InsertParameters.Add("Total", TypeCode.Double, TotalUnitPrice) SqlDataSource2.InsertParameters.Add("Quantity", TypeCode.Int32, textBoxText) SqlDataSource2.Insert()Next
|||

Try this after your insert:

SqlDataSources2.InsertParameters.Clear();

There is another way to do this. Declare your parameters first, then assign the InsertParameters' default values for each InsertParameter after the insert.

SqlDataSource2.InsertParameters("Parameter1").DefaultValue=valueofParameter1

...

|||Omg .. thanks a lot ! It works... Haha ...

No comments:

Post a Comment