【发布时间】:2014-02-17 01:17:10
【问题描述】:
你好,需要你的帮助来确定这段代码有什么问题, 这用于从复选框列表多项选择中填充一个 sql 数据库,但是 没有给出需要的结果。
我需要将每个选择保存在同一行的列中,但是当 每次它给出相同的以下结果时运行它
field_1 field_2 field_3 id
test2 test3 test4 1
即使是选定的值(测试 5、测试 6、测试 7)也不是(测试 2、测试 3、 测试 4) 来自 cbl。
非常感谢您的帮助 :)
Test.aspx.vb
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
' Define data objects
Dim myConn As SqlConnection
Dim cmd As SqlCommand
Dim sqlstring As String
' Read the connection string
myConn = New SqlConnection("Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\EmailEngineDB.mdf;Integrated Security=True")
' Create command
sqlstring = " INSERT INTO TestTBL (field_1, field_2, field_3) VALUES (@field_1, @field_2, @field_3)"
cmd = New SqlCommand(sqlstring, myConn)
' Add command parameters
For i As Integer = 0 To CheckBoxList1.Items.Count - 1
If CheckBoxList1.Items(i).Selected Then
cmd.Parameters.Add("@field_" + i.ToString(), Data.SqlDbType.NVarChar)
cmd.Parameters("@field_" + i.ToString()).Value = CheckBoxList1.Items(i).Text
End If
Next
' Enclose database code in Try-Catch-Finally
Try
' Open the connection
myConn.Open()
' Execute the command
cmd.ExecuteNonQuery()
' Display success message
Label1.Text = "Created Successfully :)"
' Reload page if the query executed successfully
' Response.Redirect("SamplesCollector.aspx")
Catch ex As Exception
' Display error message
Label1.Text = "Error ! Please try again "
Finally
' Close the connection
myConn.Close()
'Response.Redirect("SamplesCollector.aspx")
End Try
End Sub
Test.aspx
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Test.aspx.vb" Inherits="Test" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Test</title>
</head>
<body>
<form id="form1" runat="server">
<asp:CheckBoxList ID="CheckBoxList1" runat="server" AutoPostBack="True">
<asp:ListItem>test 1</asp:ListItem>
<asp:ListItem>test2</asp:ListItem>
<asp:ListItem>test 3</asp:ListItem>
<asp:ListItem>test 4</asp:ListItem>
<asp:ListItem>test 5</asp:ListItem>
<asp:ListItem>test 6</asp:ListItem>
<asp:ListItem>test 7</asp:ListItem>
<asp:ListItem>test 8</asp:ListItem>
</asp:CheckBoxList>
<br />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<br />
<asp:Button ID="Button1" runat="server" Text="Button" />
</form>
</body>
</html>
【问题讨论】:
标签: vb.net checkboxlist