[2 days left] What’s wrong with your cloud strategy? Learn why multicloud solutions matter with Nimble Storage.Register Now

x
?
Solved

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

Posted on 2014-03-18
9
Medium Priority
?
2,003 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
[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 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
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 

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

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say 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

It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
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
Video by: ITPro.TV
In this episode Don builds upon the troubleshooting techniques by demonstrating how to properly monitor a vSphere deployment to detect problems before they occur. He begins the show using tools found within the vSphere suite as ends the show demonst…
This tutorial will teach you the special effect of super speed similar to the fictional character Wally West aka "The Flash" After Shake : http://www.videocopilot.net/presets/after_shake/ All lightning effects with instructions : http://www.mediaf…
Suggested Courses

649 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