Solved

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

Posted on 2014-03-18
9
1,750 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:kqureshi321
  • 4
  • 3
9 Comments
 
LVL 39

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:kqureshi321
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 39

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
 

Author Comment

by:kqureshi321
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
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 52

Accepted Solution

by:
Scott Fell,  EE MVE earned 250 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 39

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:kqureshi321
ID: 39939872
Even with this change, the page still blinks like it reloads.
0
 
LVL 39

Assisted Solution

by:Kyle Abrahams
Kyle Abrahams earned 250 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

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

IntroductionWhile developing web applications, a single page might contain many regions and each region might contain many number of controls with the capability to perform  postback. Many times you might need to perform some action on an ASP.NET po…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…
This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're looking for how to monitor bandwidth using netflow or packet s…

758 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

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now