Count number of checkbox checked - c#

I have multiple individual checkbox's (50).
like this:
<asp:CheckBox runat="server" ID="chkBirthDate" />
I need to know how many checkbox the user has selected (Count). If he has selected more than 3 i let him pass if not i present him an error message.
Thanks in advance!

LINQ Approach
You could take advantage of the querying capability of LINQ by using the OfType<T>() method to grab all of your individual CheckBox Controls and then use a Count() call to see how many were actually checked :
// Get the number of CheckBox Controls that are checked
var checkedBoxes = Form.Controls.OfType<CheckBox>().Count(c => c.Checked);
// Determine if your specific criteria is met
if(checkedBoxes > 3)
{
// You shall pass!
}
else
{
// None shall pass
}
You'll need to ensure that you have a reference to LINQ for this to work as well by including the following using statement :
using System.Linq;
Iterative Looping Approach
Alternatively, you could simply loop through and increment a count accordingly via a foreach loop as seen below :
// Store your count
var checkedBoxes = 0;
// Iterate through all of the Controls in your Form
foreach(Control c in Form.Controls)
{
// If one of the Controls is a CheckBox and it is checked, then
// increment your count
if(c is CheckBox && (c as CheckBox).Checked)
{
checkedBoxes++;
}
}
Example (with output)
You can find a GitHub Gist that fully reproduces this here and demonstrated below :

Related

Check if Combo box is empty C#

I am trying to check if a combo box is empty using C# in a Windows Application Form. Below are two possible ways:
if (string.IsNullOrEmpty(comboBox1.Text))
if (comboBox1.SelectedIndex == -1)
In order to ensure that the user would ONLY select a value from the drop down and NOT write it s own answer, which is the best approach?
From my research the second method (if (comboBox1.SelectedIndex == -1)) will satisfy my needs. Am l right?
If your concern is only making sure that users choose an item from the list available, simply change your combobox's DropDownStyle to DropDownList
or if you want to allow them to type but then ensure it is on the list, you can do something like this:
var txt = comboBox1.Text;
if(string.IsNullOrEmpty())
return;
var test = comboBox1.Items?.OfType<string>().ToList().Any(x => x?.Trim() == txt?.Trim());
so if test is false, it means what they have selected/typed does not exist in list of available items
for combobox you can use this code below to check if it's empty or not
if(comboBox1.Items.Count == 0 )
{
// your code
}
This is what i try and it 's work. Feel free to comment:
if (comboBox1.SelectedIndex > -1 )

Selecting multiple Listbox items through code

Hi there I have searched for a while now and can't seem to find a solution to my problem, I have tried multiple methods to select multiple items in my listbox through code however none have worked, The best result I got was 1 selected item in my listbox.
Basically I want to select multiple items of the same value.
below is my code, sorry if I seem newbie but I am new to programming and still learning basic stuff.
foreach (string p in listBox1.Items)
{
if (p == searchstring)
{
index = listBox1.Items.IndexOf(p);
listBox1.SetSelected(index,true);
}
}
So as you can see I am trying to tell the program to loop through all the items in my listbox, and for every item that equals "searchstring" get the index and set it as selected.
However all this code does is select the first item in the list that equals "searchstring" makes it selected and stops, it doesn't iterate through all the "searchstring" items.
As suggested in the comment, you should set SelectionMode to either MulitSimple or MultiExpanded depending on your needs, but you also need to use for or while loop instead offoreach, because foreach loop doesn't allow the collection to be changed during iterations. Therefore, even setting this Property won't make your code run and you will get the exception. Try this:
for(int i = 0; i<listBox1.Items.Count;i++)
{
string p = listBox1.Items[i].ToString();
if (p == searchstring)
{
listBox1.SetSelected(i, true);
}
}
You can set SelectionMode either in the Properties window when using designer or in, for instance, constructor of your Form using this code:
listBox1.SelectionMode = System.Windows.Forms.SelectionMode.MultiSimple;

ASP.NET Trying to find if a ID I have is one the child controls of a CheckBoxList control

I am stuck on this issue and cannot seem to find a way around it.
I have a CheckBoxList control. If you did not know, the FindControl() method on the CheckBoxList control returns "this". Microsoft did it because internally they dont create many ListItem objects but just one.
Anyway, I am trying to find out if a posted back control is one of the controls in my CheckBoxList. My code looks something along the lines of:
if (!(System.Web.UI.ScriptManager.GetCurrent(Page) == null)) {
string postbackControlId = System.Web.UI.ScriptManager.GetCurrent(Page).AsyncPostBackSourceElementID;
if (!string.IsNullOrEmpty(postbackControlId))
{
Control control = ControlFinder.RecursiveFindChildControl(Controls, postbackControlId);
if (!(control == null))
{ }
}
}
Is there anyway to enumerate the child controls of a CheckBoxList or find if an ID that I have is equal to one of theirs?
Thanks,
Mike
The UniqueID of a CheckBox within a CheckBoxList is the UniqueID of the CheckBoxList plus a $ plus the index of the item, so you can check whether postbackControlId is one of the CheckBox controls like this:
if (postbackControlId.StartsWith(this.checkBoxList.UniqueID + "$"))
{
int itemIndex = Convert.ToInt32(
postbackControlId.Substring(this.checkBoxList.UniqueID.Length + 1), 10);
// ...
}
If you're only looking to find out whether the postback was caused by one of the items in the CheckBoxList, you don't need to traverse the entire control hierarchy. You don't even need to drill down into the list. Something like this should work fine:
string elementID = ScriptManager.GetCurrent(Page).AsyncPostBackSourceElementID;
if (elementID.Contains(chkList.UniqueID))
{
//one of the checkboxes caused the postback
}

disable dropdownlist items

I want to disable every fifth item in a dropdownlist.
dropdownlist1.items[i].Attributes.Add("disabled","disabled");
How do I write the logic to disable every fifth item in a Dropdownlist?
I am using two for loops: one for displaying items and one for disabling items in dropdownlist. How can I simplify my code?
Perhaps you should consider just not showing them?
As in:
if (i % 5 > 0) {
dropdownlist1.items[i].Attributes.Add("disabled","disabled");
}
foreach(Control c in this.Controls)
{
if(c is dropdownlist)
{
dropdownlist dl = (dropdownlist)c;
if (i % 5 > 0)
{
dl.items[i].Attributes.Add("disabled","disabled");
}
}
}
Check this out! same as castirng.
findout all dropdownlist on the form and
on every dropdown list it will disable.
let me know!!
If what you need is like an optgroup functionality to group your options. Here is a sample of what an optgroup looks like in case you don't know http://www.w3schools.com/tags/tryit.asp?filename=tryhtml_optgroup.
There are ways to add an optgroup to a dropdown list http://weblogs.asp.net/jeff/archive/2006/12/27/dropdownlist-with-optgroup.aspx
then you could use it like this
ListItem item = new ListItem("some group name", String.Empty);
item.Attributes["optgroup"] = "optgroup";
myDropDown.Items.Add(item);
or in your case
dropdownlist1.items[i].Attributes["optgroup"] = "optgroup";
Using jQuery
var count = 0;
$('select option').each(function() {
count++;
if(count % 5 == 0)
$(this).attr('disabled', 'disabled');
}):
I googled for "disable dropdownlist items" and the first result provided the exact answers you're looking for.
It's not possible, but there are alternatives.

Retrieve DataItem from RepeaterItem after databinding (during an event handler)

I'm trying to find a way to to do something that I think must be possible but I'm just missing the point on - so hopefully someone can give me a bit of a nudge :)
I'm utilising databinding in ASP.NET (viewstate turned off - so using controlstate for a few things here and there) to render a repeater (repeaterPriceClasses) that has a repeater within each itemtemplate (repeaterPriceBands). Basically this renders a table out of some text and a dropdownlist in each cell.
I'm trying to find a way to enumerate the repeaterOuter inside the event handler of a button to give me a list of all of the originally bound elements that have now got a dropdownlist with a value of >0, along with what that value is.
public Dictionary<Price, int> SelectedPrices
{
get
{
var sel = new Dictionary<Price, int>();
foreach(RepeaterItem itemClass in repeaterPriceClasses.Items)
{
var repeaterPriceBands = itemClass.FindControl("repeaterPriceBands") as Repeater;
foreach(RepeaterItem itemBand in repeaterPriceBands.Items)
{
var context = (Price)itemBand.DataItem;
var listQty = itemBand.FindControl("listQty") as DropDownList;
if(listQty.SelectedValue.ToInt32() > 0)
{
sel.Add(context, listQty.SelectedValue.ToInt32());
}
}
}
return sel;
}
}
Now this fails because the itemBand.DataItem is always null after databinding has finished.
What technique should I use to get around this?
Hidden field with primary keys in it
(not ideal as can be abused and adds
weight to the page)
Lookup from
original cached data based on indexes
(just seems wrong)
or something
else/better...?
EDIT: Is there any more information that I could provide to help this get answered?
You can try adding extra attributes to your HTML elements in the ItemDataBound event when DataItem is available.
ddlSomething.Attributes["Attribute1"] = dataItemObject.PropertyName;
[Edit]
Apart from using attributes, you can render some array containing JSON objects like this, for each row.
var repeaterItemAttributes = [ { Prop1: val1, Prop2: val2, ... }, { ... }, ... ]
So, by using this, you won't have to render the attributes, and your code will be XHTML compliant too (tho its not required). You can then loop through the object array and read any property you like. You can also apply the light encryption you were talking about to the property values.
[/Edit]

Categories

Resources