?
Solved

C#, ASP  How to check how many check boxes are checked

Posted on 2014-03-18
9
Medium Priority
?
2,049 Views
Last Modified: 2014-04-11
Hello,
We have a web page with dynamically loaded check boxes (depends on how many records in database).
What i need is to make sure the user checks only 5 check boxes. And if he checks the 6th one, give him a message that he can only check 5.
ASP:
Please select up to five:
<asp:Repeater runat="server" ID="rptCandidats" >
        <ItemTemplate>
             <div>
                 <asp:checkbox id="chResponse" runat="server"  AutoPostBack="True"   OnCheckedChanged="Check_Clicked"></asp:checkbox>
<%# Eval("ResText")%> <a href="<%#Eval("ResLink")%>" class="moreinfo">   More Info</a>
                 <asp:HiddenField ID="ResId" runat="server" Value ='<%#Eval("ResponId")%>' />                           </div>
       </ItemTemplate>
</asp:Repeater>

Open in new window

I tried to use OnCheckedChanged event, but it doesn't work.
Below is a C# code:
protected void Check_Clicked(Object sender, EventArgs e)
       {
           int checkedCount = 0;
           foreach (RepeaterItem r in rptCandidats.Items)
           {
              CheckBox cb = (CheckBox)r.FindControl("chResponse");
               if (cb.Checked)
               {
                   checkedCount += (sender as CheckBox).Checked ? 1 : -1;
               }
           }
           if (checkedCount > 5)
           {
               System.Web.HttpContext.Current.Response.Write("<SCRIPT LANGUAGE=\"JavaScript\">alert(\"Only Up to five candidates can be selected.\")</SCRIPT>");
           }

       }

Open in new window

Any ideas how can i achieve it?
Thanks.
0
Comment
Question by:Galina Besselyanova
  • 4
  • 3
8 Comments
 
LVL 41

Expert Comment

by:Kyle Abrahams
ID: 39937648
Don't use response.Write.

use ScriptManager.RegisterStartupScript:
http://msdn.microsoft.com/en-us/library/bb359558%28v=vs.110%29.aspx


 string javaScript = "<script language=JavaScript>\n" + "alert('Only Up to five candidates can be selected');\n" + "</script>";

ScriptManager.RegisterStartupScript(updatePanelId,updatePanelId.GetType()
                                                      , "alert", javaScript, true);
0
 

Author Comment

by:Galina Besselyanova
ID: 39937775
Thanks!
Here is my new code
 protected void Check_Clicked(Object sender, EventArgs e)
       {
           string sysAlert="Only up to five selections.";
           int checkedCount = 0;
           foreach (RepeaterItem r in rptCandidats.Items)
           {
               CheckBox cb = (CheckBox)r.FindControl("chResponse");
               if (cb.Checked)
               {
                   checkedCount += (sender as CheckBox).Checked ? 1 : -1;
                   if (checkedCount > 5)
                   {
                      
       Page.ClientScript.RegisterStartupScript(this.GetType(), "This Alert", "alert('" + sysAlert + "');", true);
       cb.Checked = false;

                   }
               }
           }
          
       }

Open in new window

It is working, but now, when you click on the check box, the page blinking like it reloads .
0
 
LVL 41

Expert Comment

by:Kyle Abrahams
ID: 39937803
take it out of the for each. and do you have your repeater ajaxified in an updatepanel?

protected void Check_Clicked(Object sender, EventArgs e)
       {
           string sysAlert="Only up to five selections.";
           int checkedCount = 0;
           foreach (RepeaterItem r in rptCandidats.Items)
           {
               CheckBox cb = (CheckBox)r.FindControl("chResponse");
               if (cb.Checked)
               {
                   checkedCount += cb.Checked ? 1 : 0;
                }
           }
          
        if (checkedCount > 5)
        {

       Page.ClientScript.RegisterStartupScript(this.GetType(), "This Alert", "alert('" + sysAlert + "');", true);
       cb.Checked = false;
        }

       } 

Open in new window

0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 

Author Comment

by:Galina Besselyanova
ID: 39937993
I'm sorry, i'm new to it.
There is no updatepanel.
And why remove For each if i need to count how many check boxes are already checked?
Am i doing something wrong?
0
 
LVL 54

Accepted Solution

by:
Scott Fell,  EE MVE earned 1000 total points
ID: 39938481
I'm not a .NET dev.   An alternative would be to do this in javascript and avoid the call to the server.  You would still want to test serverside for more than 5 checks.  This is one way to do what I think you want on the front end.

A live sample http://jsbin.com/visiy/1/edit where I used the jquery docs as the base.  http://api.jquery.com/checked-selector/
<!DOCTYPE html>
<html>
<head>
<style>
  .error{background-color:pink;padding:5px;}
  </style>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
  <script>
    $(function() {
    var countChecked = function () {
    var n = $("input.chResponse:checked").length;
    if (n > 5) {
        $('#myButton').prop('disabled', true);
       
        $('div.msg').addClass('error').html('You have checked more than 5 boxes.  The submit button has been disabled.  Please check only 5 boxes');
    } else {
        $('#myButton').prop('disabled', false);
        $('div.msg').removeClass('error').html('Please check no more than 5 boxes');
    }
};
countChecked();

$("input[type=checkbox].chResponse").on("click", countChecked);
    });      
  </script>
</script>
  <meta charset="utf-8">
  <title>EE Q_28391393</title>
</head>
<body>
<input type="checkbox" class="chResponse">check1<br>
<input type="checkbox" class="chResponse">check2<br>
<input type="checkbox" class="chResponse">check3<br>
<input type="checkbox" class="chResponse">check4<br>
<input type="checkbox" class="chResponse">check5<br>
<input type="checkbox" class="chResponse">check6<br>
<input type="checkbox" class="chResponse">check7<br>
<input type="checkbox" class="chResponse">check8<br>
  <div class="msg">Please check no more than 5 boxes</div>
  <button id="myButton">Submit</button>
</body>
</html>

Open in new window

0
 
LVL 41

Expert Comment

by:Kyle Abrahams
ID: 39939681
@kqureshi321

If you see the code I modified I still use the for each, I just moved the register script out of it.  

http://www.experts-exchange.com/Programming/Languages/C_Sharp/Q_28391393.html#a39937803
0
 

Author Comment

by:Galina Besselyanova
ID: 39939872
Even with this change, the page still blinks like it reloads.
0
 
LVL 41

Assisted Solution

by:Kyle Abrahams
Kyle Abrahams earned 1000 total points
ID: 39940364
that's coming from the postback.


add this to your front end:

<asp:UpdatePanel runat="server" id="UpdatePanel1">
<ContentTemplate >
  <! --- repeater goes in here -->
</ContentTemplate >
</UpdatePanel>

You can also take the javascript approach . . . but I've never been a fan of it for maintenance reasons.
0

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

ASP.Net to Oracle Connectivity Recently I had to develop an ASP.NET application connecting to an Oracle database.As I am doing it first time ,I had to solve several problems. This article will help to such developers  to develop an ASP.NET client…
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
Is your data getting by on basic protection measures? In today’s climate of debilitating malware and ransomware—like WannaCry—that may not be enough. You need to establish more than basics, like a recovery plan that protects both data and endpoints.…
Despite its rising prevalence in the business world, "the cloud" is still misunderstood. Some companies still believe common misconceptions about lack of security in cloud solutions and many misuses of cloud storage options still occur every day. …
Suggested Courses
Course of the Month13 days, 16 hours left to enroll

809 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question