如何从checkboxlist中插入多个值

时间:2015-10-27 00:47:52

标签: c# asp.net

我有一个CheckBoxList控件和更新按钮:

<asp:CheckBoxList ID="moduleselect" runat="server" DataSourceID="semester2" DataTextField="module_name" DataValueField="module_id"></asp:CheckBoxList>
            <br />
                <asp:Button ID="uploadbutton" runat="server" Text="Choose Modules" OnClick="uploadbutton_Click" CssClass="submitbtn" />
                <asp:Button ID="CancelButton" runat="server" CommandName="Cancel" Text="Cancel" CssClass="submitbtn" />

这包含供学生选择的模块列表,当点击上传按钮时,它应该更新数据库表。

我有以下C#

public partial class test : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        String name = Request.QueryString["studentno"];
        username.Text = name;
    }
    protected void uploadbutton_Click(object sender, EventArgs e)
    {
        String user = username.Text;

        string ConnectionString = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        SqlConnection myConnection = new SqlConnection(ConnectionString);

        myConnection.Open();

        int count = moduleselect.Items.Count;

        for (int i = 0; i < count; i++)
        {
            if (moduleselect.Items[i].Selected)
            {
                string value = moduleselect.Items[i].Value;

                String query = "INSERT INTO students_vs_modules (student_no, module_id) VALUES (@student_no, @module_id)";

                SqlCommand myCommand = new SqlCommand(query, myConnection);
                myCommand.Parameters.AddWithValue("@student_no", user);
                myCommand.Parameters.AddWithValue("@module_id", value);

                myCommand.ExecuteNonQuery();

                myConnection.Close();
            }
        }  
    }
}

但是,当我单击上传按钮时选择多个模块时,它只会更新所选的初始选项而不是所有选项。我对网络开发很陌生,所以任何帮助都会受到高度赞赏。

1 个答案:

答案 0 :(得分:2)

首先,您需要循环来获取checkbox的选中值。使用SelectedValue只会获得value selected

的第一个int count = moduleselect.Items.Count; for(int i = 0; i < count; i++) { if (moduleselect.Items[i].Selected) { string value = moduleselect.Items[i].Value; // Do Insert } }

例如,如下所示

int count = moduleselect.Items.Count;
string value = string.Empty;            

for(int i = 0; i < count; i++)
{
    if (moduleselect.Items[i].Selected)
    {
        value = moduleselect.Items[i].Value + ",";
    }
}

// Trim the last ,
value = value.TrimEnd(',');

// Insert here

这会插入很多不同模块的线路..
如果要添加1行并分隔,
如下所示

null