I have a CheckBoxList which includes all modules available for student to select. The number of choices can vary depending on the student and their degree.

<asp:CheckBoxList ID="module_semester_1" runat="server" DataSourceID="semester1" DataTextField="module_name" DataValueField="module_id" ></asp:CheckBoxList>
            <asp:Button CommandName="NextView" ID="btnnext2" runat="server" Text="Next" OnClick="btnnext2_Click" />

Now, I want to set a limit so that students can only select 3 modules from the CheckBoxList, how would I go about this using C# and how can I display an error message to inform students to only select 3? Any help would be greatly appreciated. I currently have the C# below:

protected void btnnext2_Click(object sender, EventArgs e)
    {
        String user = username.Text;

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

        myConnection.Open();

        int count = module_semester_1.Items.Count;

        for (int i = 0; i < count; i++)
        {
            if (module_semester_1.Items[i].Selected)
            {
                string value = module_semester_1.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();
    }

Related posts

Recent Viewed