[英]Set Maximum selection in CheckBoxList control
I have a CheckBoxList which includes all modules available for student to select. 我有一个CheckBoxList,其中包括所有可供学生选择的模块。 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? 现在,我要设置一个限制,以使学生只能从CheckBoxList中选择3个模块,如何使用C#进行处理,如何显示错误消息以通知学生仅选择3个模块? Any help would be greatly appreciated.
任何帮助将不胜感激。 I currently have the C# below:
我目前有以下C#:
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();
}
You can use a jquery to warn user. 您可以使用jquery来警告用户。 This is lightweight as it does not require round trip to server.
这是轻量级的,因为它不需要往返服务器。
<script type="text/javascript">
var limit = 3;
$(function () {
$('[id*="module_semester_1"]').on('change', function (evt) {
if ($('[id*="module_semester_1"]:checked').length > limit) {
this.checked = false;
alert('cannot select more than ' + limit);
}
});
});
</script>
<asp:CheckBoxList ID="module_semester_1" runat="server">
<asp:ListItem Value="1">1</asp:ListItem>
<asp:ListItem Value="2">2</asp:ListItem>
<asp:ListItem Value="3">3</asp:ListItem>
<asp:ListItem Value="4">4</asp:ListItem>
<asp:ListItem Value="5">5</asp:ListItem>
</asp:CheckBoxList>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.