Sunday, February 19, 2012

Commit a loop of inserting

I use loop to insert few record into a table:
But the for_Loop only loop once and throw an error:
"The variable name '@.res_name' has already been declared. Variable names must be unique within a query batch or stored procedure."
What should i do to get this fix?

Code:

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

Dim DataSources1 As New SqlDataSource()
DataSources1.ConnectionString = ConfigurationManager.ConnectionStrings("ConnectionString").ToString()

DataSources1.InsertCommandType = SqlDataSourceCommandType.Text
DataSources1.InsertCommand = "INSERT INTO cust_order (res_name, my_menu) VALUES (@.res_name, @.my_menu)"

Dim c As Integer
For c = 0 To selectListBox.Items.Count - 1 Step +2

DataSources1.InsertParameters.Add("res_name", selectListBox.Items(c).Text)
DataSources1.InsertParameters.Add("my_menu", selectListBox.Items(c + 1).Text)
DataSources1.Insert()
Next
End Sub

your loop is trying the re-add the same parameters on each pass.

For c = 0To selectListBox.Items.Count - 1Step +2 DataSources1.InsertParameters.Add("res_name", selectListBox.Items(c).Text) DataSources1.InsertParameters.Add("my_menu", selectListBox.Items(c + 1).Text) DataSources1.Insert() DataSources1.InsertParameters.Clear()'remove the previous parametersNext

you can clear them after you perform the insert so they can then be re-added with new values on the next pass through the loop

|||thanks, now the loop works fine.

No comments:

Post a Comment