通过我的CheckBoxList循环只插入一条记录

时间:2011-08-25 19:40:32

标签: asp.net vb.net checkbox

标题说我的问题 - 这是我的复选框一次只能插入一条记录。弹出模式并点击2个复选框,但只有一个插入我的数据库并显示在我的页面上。我必须一次勾选方框1,我有很多复选框。这是我的代码。 :)提前致谢

<!-- Add a Feature -->
    <li>
        <asp:LinkButton ID="FeatureButton" runat="server">Feature</asp:LinkButton>
        <asp:Panel ID="FeaturePanel" runat="server" CssClass="modalPopup" Style="display:none">
            <asp:CheckBoxList ID="cbxAddFeature" runat="server" DataSourceID="dsNewFeatures" DataTextField="FeatureTitle" DataValueField="FeatureID"></asp:CheckBoxList>
            <asp:Button ID="SubmitFeatures" runat="server" Text="Submit" /><asp:Button ID="CancelSubmitFeatures" runat="server" Text="Cancel" />
        </asp:Panel>
        <asp:ModalPopupExtender ID="FeatureModal" runat="server" BackgroundCssClass="modalBackground" CancelControlID="CancelSubmitFeatures" DropShadow="True" DynamicServicePath="" Enabled="True" PopupControlID="FeaturePanel" TargetControlID="FeatureButton"></asp:ModalPopupExtender>
    </li>

Protected Sub SubmitFeatures_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles SubmitFeatures.Click
  FeatureModal.Hide()
    For Each feature As ListItem In cbxAddFeature.Items
      If feature.Selected Then

       'SQL INSERT: Marketing Table
       Dim strSQL As String = "INSERT INTO Marketing (ProductID, MarketingTypeID, MarketingTitle, MarketingData) VALUES (@ProductID, 3, 'Feature', @MarketingData)"

       Using cn As New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("LocalSqlServer").ConnectionString)

       Using cmd As New SqlCommand(strSQL, cn)

        cmd.Parameters.Add(New SqlParameter("@ProductID", ProductID.Value))
        cmd.Parameters.Add(New SqlParameter("@MarketingData", feature.Value))

        cn.Open()

        cmd.ExecuteNonQuery()
        End Using
       End Using
End If
Next
 Response.Redirect(Request.RawUrl)
End Sub

2 个答案:

答案 0 :(得分:2)

在循环中第一次传递后不要重定向:

For Each feature As ListItem In cbxAddFeature.Items
        If feature.Selected Then
            Dim sqlAddFeatures As String = Nothing
            'SQL INSERT: Marketing Table
            sqlAddFeatures = "INSERT INTO Marketing (ProductID, MarketingTypeID, MarketingTitle, MarketingData) VALUES (" & ProductID.Value & ",3, 'Feature', " & feature.Value & ")"
            sqlAddFeatures.Replace("'", "''")
            Dim SqlConnection As New SqlConnection("Server=off-db1;uid=productsDB_admin;pwd=*****;database=Products")
            SqlConnection.Open()
            Dim sqlCommand As New SqlCommand(sqlAddFeatures, SqlConnection)
            sqlCommand.ExecuteNonQuery()
            SqlConnection.Close()
            'Response.Redirect(Request.RawUrl) 
        End If
    Next

答案 1 :(得分:0)

jlg,您将无法在SQL中一次性插入所有行。您没有指定正在使用的SQL版本,但在SQL Server 2008中,您可以将DataTable参数传递给存储过程,然后同时插入所有记录。

这要求您创建一个用户定义的数据类型,其结构与DataTable完全相同。 Read here.

或者如果你不想走那条路......

You can at least use transactions