how to Check any 2 checkBox from 4 CheckBoxes? - c#

Good Afternoon Developer,
this is my content in asp .net, I want the user can check only 2 checkbox,exceeding that alert box should pop up.
<body>
<form id="form1" runat="server">
<div>
<table width="100%">
<tr>
<td>
<asp:CheckBox id="q3a" runat="server" Text="Public" />
</td>
<td>
<asp:CheckBox id="q3b" runat="server" Text="void" />
</td>
<td>
<asp:CheckBox id="q3c" runat="server" Text="protected"/>
</td>
<td>
<asp:CheckBox id="q3d" runat="server" Text="return" />
</td>
</tr>
</table>
<asp:Button ID="btnSubmit" Text="submit" runat="server"/>
</div>
</form>
</body>
how can i write javascript for this, i have tried but can't find any way out, Pls help...

You should stop the user the instant they try and select a third option so that only two checked values can ever be submitted and avoid server side validation.
The client side onchange event should be hooked up to a function similar to this;
function validationCheck(checkbox) {
if(checkbox.checked) {
var count = 0;
count += document.getElementById('q3a').checked ? 1 : 0;
count += document.getElementById('q3b').checked ? 1 : 0;
count += document.getElementById('q3c').checked ? 1 : 0;
count += document.getElementById('q3d').checked ? 1 : 0;
if(count > 2) {
alert('You may only select two options.');
checkbox.checked = false;
}
}
}
The input should render with onchange="validationCheck(this);".

You could use JQuery:
$("input[type='checkbox']").change(function () {
var n = $("input:checkbox:checked").length;
if (n > 2) {
alert('2 are already selected!');
$(this).attr("checked", false);
}
});
If you really want to use JavaScript try this function:
function checkCondition(chkbox) {
var buttonGroup = document.getElementsByName("group");
var total = 0;
for (var i = 0; i < buttonGroup.length; i++) {
if (buttonGroup[i].checked) {
total++;
}
}
if (total > 2) {
alert('2 are already selected!');
chkbox.checked =false;
}
}
And also set onclick="checkCondition(this)" on your checkboxes and set their name attribute to the group value for example

agree with #Tim you can just write an on_click function for all checkboxes and then validate there if more then two chekboxes are selected and display error message when needed.

You could use jQuery to find all selected checkboxes:
var count = $("input:checked").length;
Then you have all you need.
But i would recommend to use the builtin ASP.NET-Validator Controls. You could use a CustomValidator for this purpose which would also work on clientside with an appropriate ClientValidationFunction.

You could add a client side onclick event for the check box and using jQuery you can check if the check box is checked. You can have a counter that should measure the threshold and then pop up the message if it exceeds.
$('.mycheckbox').click(function(){
var count = $("input:checked").length;
}
Note: Please add a classname property to all the checkboxes with same class name.

Related

Calculating score on a quiz test using asp.net C# with database

I'm trying to create a quiz in web application in asp.net C# using a database. The quiz has 25 question and 5 answers and each answer has a number of points(totally agree(1),agree(2), not sure(3), disagree(4), totally disagree(5)).
The questions and answers are in a database.
What I want is when i click on the submit button to calculate the score from those questions and put the score in a table from my database.
I try to do a if (radiobutton1.checked){
score=2}
but it doesn't work because of the repeater...I guess i'm not sure.
I try to delete the repeater but when i done that the questions and answers do not display on the web page.
In my aspx file i write code to display my data from database like that(using a repeater and table):
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<table>
<tr>
<td> <%#Eval("IDq") %> ) <%#Eval("qustion") %></td></tr>
<tr>
<td>
<asp:RadioButton ID="RadioButton1" runat="server" Text='<%#Eval("ans1")%>' GroupName="quiz" Value="1"></asp:RadioButton>
<asp:RadioButton ID="RadioButton2" runat="server" Text='<%#Eval("ans2") %>' GroupName="quiz" Value="2"></asp:RadioButton>
<asp:RadioButton ID="RadioButton3" runat="server" Text='<%#Eval("an3") %>' GroupName="quiz" Value="3"></asp:RadioButton>
<asp:RadioButton ID="RadioButton4" runat="server" Text='<%#Eval("ans4") %>' GroupName="quiz" Value="4"></asp:RadioButton>
<asp:RadioButton ID="RadioButton5" runat="server" Text='<%#Eval("ans5") %>' GroupName="quiz" Value="5"></asp:RadioButton>
<br />
</td>
</tr> </table>
</ItemTemplate></asp:Repeater>
Ok, you have a good start.
And I am going to suggest that in place of the RadioGroup tag?
That DOES get you automatic ONLY one choice. The problem is we STILL will have to check all 5 controls.
A better control in this case to use what is called a RadioButtonList. It works VERY much like having used RadioGroup, but the REALLY nice part?
It is ONE control, and if there are 3 or 15 choices for Radio button group, it as ONE control returns
the index of the selection (0 to N)
the text value of the selection
the value value of the selection.
So I recommend using a RadioButton list - since it is "one thing" that returns the selections.
The "major" problem with the RadioButtonList is you CAN'T use those cool data bound expresisons ike you are using now (that was a good call/design on your part).
However, either we write a loop to "get/check" the 5 raido buttons, or we write a loop to fill the Radiobutton list - I think using code to fill out the RadioButton list is a better choice.
Also, you new - and I see you are attempting to use some "table and "tr" to help you lay out things. You don't really need this.
Now, because ALL of the above ideas saves us so much time, so much code? Well, then we can add extra code to say
show the score and results after we submit
tell the user they did NOT answer a question - they MUST!!!
heck, toss is a cool check box, or X box to show wrong or right.
Allow a question to only have say 2 answers - not always all 5
Ok first up, our table - it looks like this:
So, we have the IDq (id of question). The 1 to 5 possible answers, and then a column with the CORRECT answer.
Ok, now our markup. As I stated, since we reduced so much markup and code, then I added the message in big bold red that appears when a user did not answer all questions.
And I also added a "results" box that shows when you hit submit (number wrong, and correct).
So, now our Markup becomes like this:
<div style="width:35%">
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<div style="float:left">
<asp:Label ID="Question" runat="server"
Text = '<%# Eval("IDq").ToString + " ) " + Eval("question") %>'
Font-Size="X-Large">
</asp:Label>
</div>
<div style="float:right">
<img id="MyImage" runat="server" src="" height="48" width="48" />
</div>
<div style="clear:both">
<asp:RadioButtonList ID="RadioButtonList1" runat="server" RepeatDirection="Horizontal" ></asp:RadioButtonList>
</div>
<br />
<hr></hr>
</ItemTemplate>
</asp:Repeater>
<asp:Button ID="cmdDone" runat="server" Text="Submit" />
<div id="MyError" style="display:none;normal;color:red" runat="server">
<h2>You have not answered all questions</h2>
<h2>Please answer all questions before submitting</h2>
</div>
<div id="Results" runat="server" style="clear:both; display:none" >
<h2>Results</h2>
<asp:TextBox ID="MyCorrect" runat="server"></asp:TextBox>
<br />
<asp:TextBox ID="InCorrect" runat="server"></asp:TextBox>
</div>
</div>
so, not a lot of markup - and we added quite a bit new features.
I also tossed in the idea to show a check box for correct, and wrong - you can remove that part - but it does help you learn a lot here.
So, now when I run the code, I see this:
So note the questions I have correct. As I stated - you may well want to remove that.
And note the message that I not yet answered all questions.
So, as noted, we have a LITTLE bit more code to load up the Repeater, but less to check things after.
So, our code now looks like this:
private DataTable MyTable = new DataTable();
protected void Page_Load(object sender, System.EventArgs e)
{
if (IsPostBack == false)
{
LoadData();
ViewState["MyTable"] = MyTable;
}
else
MyTable = ViewState["MyTable"];
}
public void LoadData()
{
using (SqlCommand cmdSQL = new SqlCommand("SELECT * from tblQuestions ORDER BY IDq",
new SqlConnection(My.Settings.TEST4)))
{
cmdSQL.Connection.Open();
MyTable.Load(cmdSQL.ExecuteReader);
Repeater1.DataSource = MyTable;
Repeater1.DataBind();
}
}
protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item | e.Item.ItemType == ListItemType.AlternatingItem)
{
DataRow MyRow = MyTable.Rows(e.Item.ItemIndex);
RadioButtonList rBtnList = e.Item.FindControl("RadioButtonList1");
for (var i = 1; i <= 5; i++)
{
var strR = "ans" + i;
if (IsDBNull(MyRow(strR)) == false)
{
ListItem nItem = new ListItem(MyRow(strR), i);
rBtnList.Items.Add(nItem);
}
}
}
}
protected void cmdDone_Click(object sender, EventArgs e)
{
// check all rows - make sure all have a answer
// show check box for correct answers
// total up correct answers (count)
// total up wrong answers (count)
MyError.Style("Display") = "none";
int Correct = 0;
int Wrong = 0;
int NotAnser = 0;
foreach (RepeaterItem ritem in Repeater1.Items)
{
RadioButtonList RadioBut = ritem.FindControl("RadioButtonList1");
if (RadioBut.SelectedIndex >= 0)
{
HtmlImage MyImage = ritem.FindControl("MyImage");
if (MyTable.Rows(ritem.ItemIndex).Item("Answer") == RadioBut.SelectedIndex + 1)
{
Correct += 1;
MyImage.Src = "/Content/ok.png";
}
else
{
Wrong += 1;
MyImage.Src = "/Content/reject.png";
}
}
else
{
NotAnser += 1;
}
}
// if missed questions then display warning.
if (NotAnser > 0)
MyError.Style("Display") = "normal";
else
{
MyCorrect.Text = "Correct answers = " + Correct;
InCorrect.Text = "Wrong answers = " + Wrong;
Results.Style("Display") = "normal";
}
}
So you can see in that submit button code, we are NOW with great ease to loop the repeater, get the user answer, check against the table data.
And note the other trick - I persist MyTable into ViewState. I did this since I did not want to have to re-load the table each time - it just means for ANY button click, control and code behind? I ALWAYS have the data table at my fingertips
Now, given the above does total up the answer, then you would have to add 2-5 more lines of code to write out the total, or the results - it not clear if you plan to have some other table where you have say some student ID, or user id, and you save the total results of the test (or the correct count, or wrong count).
so, the final result looks like this:

ASP.NET How to validate if a box within a checkboxlist is selected (1 and only 1)

I'm trying to get a little help with a validation function for an assignment of mine. I'm completely stuck on it. We had to create a web form with several fields. I've set everything else up (user name longer than 6 characters; password hidden with asterisks, longer than 8 characters, and contains 1 upper & 1 lower case letter, 1 number, and 1 special character, etc.).
The instructions is that every field needs to have a something entered. We were supposed to create various fields, but one of the instructions was to create a checkboxlist with 5 boxes. The instructions did not specify that only once answer was to be selected, however, that is what I'm going for.
The checkboxlist is for age demographics....for the user to select what age range they fall into. This is what I have:
ASPX File:
<tr class="Specific">
<td>
<asp:Label
ID="AgeLabel"
style="vertical-align:middle"
runat="server"
Text="Age Demographic:"
Font-Bold="True"
ForeColor="#016882">
</asp:Label>
</td>
<td>
<asp:CheckBoxList ID="Age" runat="server" Width="385px">
</asp:CheckBoxList>
</td>
</tr>
ASPX.CS File:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Age.Items.Add(" 18-24");
Age.Items.Add(" 25-34");
Age.Items.Add(" 35-44");
Age.Items.Add(" 45-54");
Age.Items.Add(" 55+");
MyFormPanel.Visible = true; // show the form
} // End If
} // End Page_Load
This just populates the checkboxes for me. I can't get any validator to work with this one. So what I've done is create a function to run upon clicking a Submit button. This function checks if there is only 1 box clicked.
protected void cmdSubmit_Click(object sender, EventArgs e)
{
int test = 0;
result.Text = "";
foreach (ListItem lstItem in Age.Items)
{
if (lstItem.Selected == true)
{
test += 1;
}
}
if (test == 0)
{
result.Text = "Please select one of the boxes in Age Demographic.";
}
else if (test != 1)
{
result.Text = "Please select only 1 checkbox in Age Demographic.";
}
else
{
return;
}
}
My question is...how can I tie this function back into page validation? My thought process is that there is something called Page.IsValid that is a boolean, correct? My thought was that I can put something in this function that assigns IsValid to false and if this validation goes through, then it assigns IsValid to true. Am I on the right path in thinking here?
I tried this in my code but it is telling me something about this property is read only. I've got a lot of different RequiredFieldValidators and RegularExpressionValidators already set up to make sure textboxes aren't empty and that email addresses and phone numbers are formatted correctly, so I'm not sure how this function can play in with those. Any help would be greatly appreciated. Thank you.
UPDATE: Now I'm being told that the user can select more than one checkbox, so checkboxlist is more appropriate. But how would we validate the data and include the information within the validation summary?
Do you want to check if at least one item selected in checklistbox?
If so, maybe you can try to script to achieve it. Here is a simple demo.
script
<script type="text/javascript">
function ValidateCheckBoxList(sender, args) {
var checkBoxList = document.getElementById("<%=CheckBoxList1.ClientID %>");
var checkboxes = checkBoxList.getElementsByTagName("input");
var isValid = false;
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
isValid = true;
break;
}
}
args.IsValid = isValid;
}
</script>
CustomValidator
<form id="form1" runat="server">
<div>
<asp:CheckBoxList ID="CheckBoxList1" runat="server">
<asp:ListItem>A</asp:ListItem>
<asp:ListItem>B</asp:ListItem>
<asp:ListItem>C</asp:ListItem>
<asp:ListItem>D</asp:ListItem>
</asp:CheckBoxList>
<asp:CustomValidator ID="CustomValidator1" ErrorMessage="You need to select at least one item." ForeColor="Red" ClientValidationFunction="ValidateCheckBoxList" runat="server" />
</div>
<asp:Button ID="BtnCheck" runat="server" OnClick="BtnCheck_Click" Text="Check" />
</form>
If catch the exception System.InvalidOperationException, add the following statement in Web.config
<appSettings>
<add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
</appSettings>

How do I validate multiple asp.net checkboxes in C#

I have spent a lot of time trying to get 4 checkboxes to validate in a web application. This web app has already been written, and uses checkboxes when it probably should use a checkboxlist. However, I believe it will be an inordinate amount of work to change all of the existing code, so being able to validate the existing 4 boxes would save me a total re-write.
I have been through stackoverflow looking for the answer for two days, and I found several answers that will help me if I have a single checkbox, but I can't get anything to work if I have multiple, and I just want to validate a single box.
Below is the checkbox info for the ascx form:
</asp:Panel>
<cc1:PopupControlExtender ID="PopupControlExtender1" PopupControlID="PanelTypeOwnership"
runat="server" TargetControlID="helpTypeOwnership" Position="Left">
</cc1:PopupControlExtender>
<strong> Type of Ownership:</strong></td>
<td class="style12">
</td>
<td class="style11">
</td>
<td>
<strong>
<div class="textBoxImg" id="helpTypeOwnership" runat="server" style="width: 24px;
float: right;">
</div>
</strong>
</td>
</tr>
<tr>
<td style="padding-left: 2px;" class="style2">
<asp:CheckBox ID="chbAgricultural" runat="server" CssClass="texLabel" Text=" Agricultural/Horticultural Society"
BorderStyle="None" Width="260px" />
</td>
<asp:CustomValidator runat="server" ID="validateCheckBoxes" EnableClientScript="true"
OnServerValidate="validateCheckBoxes_ServerValidate"
ClientValidationFunction="validateCheckBoxes_ServerValidate">Please select a type of ownership.</asp:CustomValidator>
<td valign="middle" align="left" class="style10">
<asp:CheckBox ID="chbEnducational" runat="server" CssClass="texLabel"
Text=" Educational" />
</td>
<td class="style12">
<asp:CheckBox ID="chbReligious" runat="server" CssClass="texLabel"
Text=" Religious" />
</td>
<td class="style11">
<asp:CheckBox ID="chbCharitable" runat="server" CssClass="texLabel"
Text=" Charitable" />
</td>
</tr> </table>
<div style="height: 39px;">
</div>
The code relating to the checkbox validation on the ascx.cs form is:
protected void validateCheckBoxes_ServerValidate(object source, ServerValidateEventArgs args)
{
if (!chbAgricultural.Checked && !chbEnducational.Checked && !chbReligious.Checked && !chbReligious.Checked)
args.IsValid = false;
else
args.IsValid = true;
}
The code for the submit button is:
protected void lbnSubmit_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
MembershipUser mUser = Membership.GetUser(Page.User.Identity.Name);
if (mUser == null) return;
DateTime dateT = Convert.ToDateTime(TextBoxDateWrite.Text);
FairShareApplication451a.changeStatusToVoid(new Guid(mUser.ProviderUserKey.ToString()), GetParcelId());
FairShareApplication451a apl451a = FairShareApplication451a.CreateApplication451a(new Guid(mUser.ProviderUserKey.ToString()),
lblNumberApplication.Text, TextBoxCounty.TextBoxText, TextBoxTaxyear.TextBoxText, TextBoxContactName.TextBoxText, TextBoxContactPhone.TextBoxText, TextBoxStateIncorporated.TextBoxText, //
GetParcelId(), chbAgricultural.Checked, chbEnducational.Checked, chbReligious.Checked, chbCharitable.Checked, TextBoxOrganizationName.TextBoxText, TextBoxPropOwnerName.TextBoxText,//
TextBoxMailingAddress.TextBoxText,
TextBoxCity.TextBoxText, DDListControl2.SelectedValue, TextBoxZipCode.TextBoxText, //TextBoxState.TextBoxText
TextBoxPropertyDescriptions.TextBoxText,
TextBoxAuthorizedSignature.Text, TextBoxTitle.Text, dateT, "Not Reviewed",
PropertyAddress.TextBoxText, PropertyCity.TextBoxText, PropertyState.SelectedValue, PropertyZip.TextBoxText); // Convert.ToDateTime(TextBoxDateWrite.Text)
//save uploaded files
SaveUploadedFiles(apl451a.Id);
FileUploader1.ResetControl();
MailSend m_snd = new MailSend(Server, Request);
m_snd.SendMessage(apl451a.UserId, FairShare.MailSend.mailType.received);
Response.Redirect("~/securezone/CurrentApplications.aspx");
// ClearAll();
}
}
I am sure I am missing something. I am still able to submit forms without checking any boxes. Any help would be greatly appreciated.
Note: I am aware educational is spelled incorrectly. I inherited this site --I just haven't gotten around to changing it in all of the relevant places.
Another option is to create a property on the ASCX user control
public bool IsOneCheckboxChecked
{
get
{
return (chbAgricultural.Checked || chbEnducational.Checked || chbReligious.Checked || chbCharitable.Checked);
}
}
You can then remove this method: (and maybe avoid a postback in the process)
protected void validateCheckBoxes_ServerValidate
and when it is time to submit the form, check:
if (userControlInstance.IsOneCheckboxChecked)
{
// good to go.
}
To check if one or more of the checkboxes is checked, you just need
args.IsValid = (chbAgricultural.Checked || chbEnducational.Checked || chbReligious.Checked || chbCharitable.Checked)
(you had chbReligious in there twice).
And I'm fairly sure you need to tie the CustomValidator to a Control to check, unless there is something else in the page which isn't shown.
Why to give up with client side validation? In your CustomValidator you have:
OnServerValidate="validateCheckBoxes_ServerValidate"
and
ClientValidationFunction="validateCheckBoxes_ServerValidate"
You have ClientValidationFunction pointing to the same server function. Try something like the following:
ClientValidationFunction="validateCheckBoxes_CLIENTValidate"
Being the client function something like this:
<script type="text/jscript">
function validateCheckBoxes_CLIENTValidate(sender, e) {
e.IsValid = jQuery(".texLabel input:checkbox").is(':checked');
}
</script>
If you cannot resolve multiple checkbox values by css class name you can take a look to this link

Maximum checked allow in CheckBoxList

I have generated a CheckBoxList which has more than one item using C#. Now I want to set a maximum number of checked item allowed in CheckBoxList. If user check more than maximum allowed item, there will be an alert or the other item will automatic uncheck to prevent user check over maximum number of item allowed.
The maximum number of checked item will be set up to ChecokBoxList in code-behind (C#) or using javascript do this, but the javascript is also should be generated in C# too.
I need some help to solve this issue.
Example Code:
CheckBoxList chkl = new CheckBoxList();
string[] items = {"item1", "item2", "item3", "item4", "item5"};
foreach (string item in items )
{
chkl.Items.Add(new ListItem(item));
}
chkl.MaximumCheck = 3;
After generated in code-behind, the CheckBoxList will only allow user to check only three items. If user check more than three item, other item will automatic uncheck or at least an alert will show to prevent user check more than three items.
I have a good solution for this issue:
In C# I will generate a CheckBoxList with 5 items using this code:
CheckBoxList chkl = new CheckBoxList();
string[] items = { "item1", "item2", "item3", "item4", "item5" };
foreach (string item in items)
{
chkl.Items.Add(new ListItem(item));
}
chkl.AutoPostBack = true;
chkl.CssClass = "3";
chkl.SelectedIndexChanged += new EventHandler(BoxChecked);
As you can see, the CheckBoxList has 5 item and the maximum checked item is seted via CssClass attribute of CheckBoxList, assumed there will be no CssClass needed in CheckBoxList. So that I will set the maximum checked item via this attribute to make it more clear. The key here is to add an EventHandler on CheckboxList, so that if user going to check more than the maximum item, other item will be disable.
The EventHander will be written as follow:
protected void BoxChecked(object sender, EventArgs e)
{
try
{
int maximumCheck = -1;
CheckBoxList CheckExpertiseList = (CheckBoxList)sender;
try {
maximumCheck = Convert.ToInt32(CheckExpertiseList.CssClass);
}
catch { }
if (maximumCheck > -1)
{
if (CheckExpertiseList.Items.Cast<ListItem>().Where(i => (i.Selected == true)).Count() == maximumCheck)
{
CheckExpertiseList.Items.Cast<ListItem>().Where(i => (i.Selected == false)).ToList().ConvertAll(i => i.Enabled = false).ToList();
}
else if (CheckExpertiseList.Items.Cast<ListItem>().Where(i => (i.Selected == true)).Count() == maximumCheck - 1)
CheckExpertiseList.Items.Cast<ListItem>().Where(i => (i.Selected == false)).ToList().ConvertAll(i => i.Enabled = true).ToList();
}
}
catch { }
}
EventHandler Event will check if the checkboxlist has over limit item checked it will disable other items, else it will reenable other item.
int x = 0;
foreach (var li in ListBox1.Items) {
if (li.Selected == true)
{
x = x + 1;
}
or like:
ListBox1.GetSelectedIndices().Length
In Javascript:
<script type="text/javascript" language="javascript">
function CheckCheck()
{
var chkBoxList=document.getElementById('<%=CheckBoxList1.ClientID %>'); var chkBoxCount=chkBoxList.getElementsByTagName("input");
var btn=document.getElementById('<%=btnSubmit.ClientID %>');
var i=0;
var tot=0;
for(i=0;i<chkBoxCount.length;i++)
{
if(chkBoxCount[i].checked)
{
tot=tot+1;
}
}
if(tot > 3)
{
alert('Cannot check more than 3 check boxes');
}
</script>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>
<asp:CheckBoxList ID="CheckBoxList1" runat="server" onclick="javascript:CheckCheck();">
<asp:ListItem>One</asp:ListItem>
<asp:ListItem>Two</asp:ListItem>
<asp:ListItem>Three</asp:ListItem>
<asp:ListItem>Four</asp:ListItem>
<asp:ListItem>Five</asp:ListItem>
</asp:CheckBoxList>
</td>
<td>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" />
</td>
</tr>
</table>
First of all, I am thank you to Jeremy Thompson. He gave me a good idea for my issue. A little bit change and I have what I want. Solve my issue only using javascript.
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<script type="text/javascript" language="javascript">
function CheckCheck() {
var chkBoxCount = this.getElementsByTagName("input");
var max = parseInt(this.className);
var i = 0;
var tot = 0;
for (i = 0; i < chkBoxCount.length; i++) {
if (chkBoxCount[i].checked) {
tot = tot + 1;
}
}
if (tot > max) {
var k = 0;
for (i = 0; i < chkBoxCount.length; i++) {
if (chkBoxCount[i].checked) {
k++;
if (k > max) {
chkBoxCount[i].checked = false;
alert('Cannot check more than ' + max + ' check boxes');
}
}
}
}
}
</script>
<div>
<table>
<tr>
<td>
<asp:CheckBoxList ID="CheckBoxList1" runat="server" CssClass="3" onclick="javascript:CheckCheck.call(this);">
<asp:ListItem>One</asp:ListItem>
<asp:ListItem>Two</asp:ListItem>
<asp:ListItem>Three</asp:ListItem>
<asp:ListItem>Four</asp:ListItem>
<asp:ListItem>Five</asp:ListItem>
</asp:CheckBoxList>
</td>
<td>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" />
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
The javascript will automatic recognize what control is going to call it, and it also get the maximum check item via attribute CssClass of control. By doing this, I also prevent user check more than maximum item in CheckBoxList without doing some post-back.
private void cb_magia_SelectedIndexChanged(object sender, EventArgs e)
{
int maxNumber = 4;
int iSelectedIndex = cb_magia.SelectedIndex;
if (cb_magia.CheckedItems.Count > maxNumber)
{
cb_magia.SetItemCheckState(iSelectedIndex, CheckState.Unchecked);
MessageBox.Show("you had checked the maximum checkbox value allowed");
}
}

Loop and add DropDown item in the Page instead of code-behind?

I wonder if is possible to add DropDown item in the Page instead of Code-behind?
So say I have a DropDown box I want to show year 1900 ~ current year
<asp:DropDownList ID="ddlYear" runat="server" CssClass="text">
<%
int currentYear = DateTime.Now.Year;
for (int i = 1900; i < currentYear; i++)
{
%>
<asp:ListItem><%=i %></asp:ListItem>
<%
}
%>
</asp:DropDownList>
Is it possible to do something like that?
Because when I try to do like above it gives me:
Warning 1 C:\SandBox\MyWebApplication1\MyWebApplication1\Default.aspx:
ASP.NET runtime error: Code blocks are not supported in this
context. C:\SandBox\MyWebApplication1\MyWebApplication1\Default.aspx 35 1 MyWebApplication1
Edit: I also tried:
<asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList>
<%
int currentYear = DateTime.Now.Year;
if (currentYear <= 1933)
{
currentYear = 2012;
}
for (int i = 1933; i < currentYear; i++)
{
DropDownList1.Items.Add(new ListItem(i.ToString(), i.ToString()));
}
%>
But the DropDownList doesn't have items when display...
=====
Edit: As Splash-X suggested, now it rendered, but all items gone after postback....
<form id="form1" runat="server">
<div>
<%
int currentYear = DateTime.Now.Year;
if (!Page.IsPostBack)
{
if (currentYear <= 1933)
{
currentYear = 2012;
}
DropDownList1.Items.Clear();
for (int i = 1933; i < currentYear; i++)
{
DropDownList1.Items.Add(new ListItem(i.ToString(), i.ToString()));
}
}
%>
<asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList>
<input id="Button1" type="button" value="button" onclick="MyFunction();"/>
<div id="MyDiv">
</div>
<asp:Button ID="Button2" runat="server" Text="Button" />
</div>
</form>
I don't beleive it is. You can have script blocks in the page rather than in the code behind but they would be coded in the same way as the codebehind would be (ie method blocks and referring to the dropdown as an object and calling add methods, etc.) so you are not really gaining anything by doing it in the page.
I had an instance where we had a project written in ASP.NET 2.0 and we no longer had the source code to make changes. We needed to modify the states that were being displayed in a dropdown. The old code had US States and Canadian Provinces and we needed to display States only. The dropdown was bound to data source in the code behind so we clear the items and then add all of the items.
<%
if(!IsPostBack)
{
st.Items.Clear();
st.Items.Add(new ListItem("State", "")); //Add an empty item at the top for default value
string usStates = "AA,AE,AK,AL,AP,AR,AS,AZ,CA,CO,CT,DC,DE,FL,FM,GA,GU,HI,IA,ID,IL,IN,KS,KY,LA,MA,MD,ME,MH,MI,MN,MO,MP,MS,MT,NC,ND,NE,NH,NJ,NM,NV,NY,OH,OK,OR,PA,PR,PW,RI,SC,SD,TN,TX,UT,VA,VI,VT,WA,WI,WV,WY";
foreach (string state in usStates.Split(','))
{
st.Items.Add(new ListItem(state, state));
}
}
%>
<select name="st" class="col" id="st" alt="select" runat="server">
The difference is I'm doing my modifications BEFORE the control and the reason I had to do this is any script that comes after the control is changing the dropdown after it is rendered out to the page.
Try moving your code above the dropdown list. Our code checks to see if there was a post back so we could preserve any value that was previously entered. There is no point reloading the list on every page load, just the first.

Categories

Resources