Solved

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

Posted on 2014-03-18
9
1,852 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
9 Comments
 
LVL 40

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 40

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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

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
 
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 40

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 40

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

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Today is the age of broadband.  More and more people are going this route determined to experience the web and it’s multitude of services as quickly and painlessly as possible. Coupled with the move to broadband, people are experiencing the web via …
Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
Although Jacob Bernoulli (1654-1705) has been credited as the creator of "Binomial Distribution Table", Gottfried Leibniz (1646-1716) did his dissertation on the subject in 1666; Leibniz you may recall is the co-inventor of "Calculus" and beat Isaac…
In an interesting question (https://www.experts-exchange.com/questions/29008360/) here at Experts Exchange, a member asked how to split a single image into multiple images. The primary usage for this is to place many photographs on a flatbed scanner…

730 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