Find if selected Checkboxes in repeater is of which gender - asp.net

I have a repeater where I have a column with checkboxes and one column with gender which i populate with database value.
I want to find out if user has selected multiple checkboxes of same gender e.g. male if so do something otherwise If a user selects multiple checkboxes with a mixture of male and female then do something else.
so far I was thinking to add this to a list and then see if list has same values but not sure if it is best idea here is my code (I have a hidden field to get gender ), I am running this on click event of a button:
foreach (RepeaterItem rptItem in myrepeater.Items)
{
hiddenGender = rptItem.FindControl("hiddenGender") as HiddenField;
if (Convert.ToInt32(hiddenGender.Value) == 0)
{
gender.Add(0);
}
else if (Convert.ToInt32(hiddenGender.Value) == 1)
{
gender.Add(1);
}
else if (Convert.ToInt32(hiddenGender.Value) == 2)
{
gender.Add(2);
}
}
ps without usage of linq as it is framework 2.0

I'm not sure if i understand what you want to do, but if i do, this code does the same:
foreach (RepeaterItem rptItem in myrepeater.Items)
{
hiddenGender = rptItem.FindControl("hiddenGender") as HiddenField;
gender.Add(Convert.ToInt32(hiddenGender.Value));
}

got it, here is the code to maybe help others(first I get the first item and see if it matches next item) :
public static bool ListEquality(IEnumerable<int> lstGender)
{
int? first = null;
bool isUnique = true;
foreach (var item in lstGender)
{
if (first == null)
{
first = item;
}
else if (first.Value != item)
{
isUnique = false;
}
}
return isUnique;
}

Related

How to persist search criteria and results of a c# .NET application page

Scenario:
User submits search criteria and selects an item from search results on the same page, which navigates to a new page of details for the selected item.
When the User returns to the search screen, the search criteria & results (including selected page and sort-order) should be preserved from their last visit.
Related information:
All form submissions are POSTs.
Navigation back to the search screen may not be available from last browser history (e.g. more than one details screen may be encountered, or the user may navigate directly to the search screen from an alternative menu.)
Search results are provided using Telerik RadGrid control.
I'm looking for a generic solution that will be able to be applied to different search screens.
In some instances, the item may be DELETED from within the details screen, and should therefore not appear in the search results when the screen is next encountered.
Thoughts:
I've read a lot of suggested methods for addressing various parts of this scenario, but I'm still confused; no comprehensively "correct" solution jumps to the forefront.
I guess I'm asking for recommendations/approach rather than a whole solution spelled out for me (although that would be nice! ;-)
The .NET VIEWSTATE would seem to do exactly what I'm after (with the exception of #5) - Is there some way of leveraging off this so that viewstate can be used between pages, and not just between postbacks to the same page? (e.g. can I store/restore viewstate to/from a session variable or something? I haven't seen this suggested anywhere and I'm wondering if there's a reason why.)
Thanks in advance.
Thanks for all the advice.
For the benefit of others, here is a solution to this issue (no doubt there's room for improvement, but this works satisfactorily for the moment).
4 functions...
StoreSearchCookie - Persist the state/values of a panel of search criteria and a results grid in a cookie with a specified UID.
RestoreSearchCookie_Criteria - Read the cookie and re-populate the search criteira
RestoreSearchCookie_Results - Read the cookie and restore the grid state.
FindFormControls - Helper method to recursively find form-input controls in a container (pinched & modified from elsewhere on Stack Overflow)
NB...
I haven't addressed the multiple-tabs issue because our application doesn't allow them anyway.
RestoreSearchResults utilises GridSettingsPersister.cs available from Telerik website, (but I had to modify it to store the page number as well)
Usage is as follows...
protected void Page_PreRender(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
// Store the state of the page
StoreSearchCookie("SomeSearchPage", pnlSearchCriteria, gridResults);
}
else
{
// Restore search criteria
RestoreSearchCookie_Criteria("SomeSearchPage");
// Re-invoke the search here
DoSearch(); // (for example)
// Restore the grid state
RestoreSearchCookie_Results("SomeSearchPage");
}
}
Code follows...
protected void StoreSearchCookie(string cookieName, Panel SearchPanel, RadGrid ResultsGrid)
{
try
{
HttpCookie cookieCriteria = new HttpCookie("StoredSearchCriteria_" + cookieName);
// 1. Store the search criteria
//
List<Control> controls = new List<Control>();
FindFormControls(controls, SearchPanel);
foreach (Control control in controls)
{
string id = control.ID;
string parentId = control.Parent.ID;
string uid = string.Format("{0}>{1}", parentId, id);
string value = "";
Type type = control.GetType();
bool isValidType = true; // Optimistic!
if (type == typeof(TextBox))
{
value = ((TextBox)control).Text;
}
else if (type == typeof(DropDownList))
{
value = ((DropDownList)control).SelectedValue;
}
else if (type == typeof(HiddenField))
{
value = ((HiddenField)control).Value;
}
else if (type == typeof(RadioButton))
{
value = ((RadioButton)control).Checked.ToString();
}
else if (type == typeof(CheckBox))
{
value = ((CheckBox)control).Checked.ToString();
}
else
{
isValidType = false;
}
if (isValidType)
{
cookieCriteria.Values[uid] = value;
}
}
cookieCriteria.Expires = DateTime.Now.AddDays(1d);
Response.Cookies.Add(cookieCriteria);
// 2. Persist the grid settings
//
GridSettingsPersister SavePersister = new GridSettingsPersister(ResultsGrid);
HttpCookie cookieResults = new HttpCookie("StoredSearchResults_" + cookieName);
cookieResults.Values["GridId"] = ResultsGrid.ID;
cookieResults.Values["GridSettings"] = SavePersister.SaveSettings();
cookieResults.Expires = DateTime.Now.AddDays(1d);
Response.Cookies.Add(cookieResults);
}
catch (Exception exception)
{
Logger.Write(exception);
}
}
protected void RestoreSearchCookie_Criteria(string cookieName)
{
try
{
HttpCookie cookieCriteria = Request.Cookies["StoredSearchCriteria_" + cookieName];
if (cookieCriteria != null)
{
foreach (string key in cookieCriteria.Values.AllKeys)
{
string value = cookieCriteria[key];
string[] ids = key.Split('>');
string parentId = ids[0];
string id = ids[1];
Control control = FindControl(parentId).FindControl(id);
Type type = control.GetType();
if (type == typeof(TextBox))
{
((TextBox)control).Text = value;
}
else if (type == typeof(DropDownList))
{
((DropDownList)control).SelectByValue(value);
}
else if (type == typeof(HiddenField))
{
((HiddenField)control).Value = value;
}
else if (type == typeof(RadioButton))
{
((RadioButton)control).Checked = Boolean.Parse(value);
}
else if (type == typeof(CheckBox))
{
((CheckBox)control).Checked = Boolean.Parse(value);
}
}
}
}
catch (Exception exception)
{
Logger.Write(exception);
}
}
protected void RestoreSearchCookie_Results(string cookieName)
{
try
{
HttpCookie cookieResults = Request.Cookies["StoredSearchResults_" + cookieName];
if (cookieResults != null)
{
string gridId = cookieResults.Values["GridId"];
string settings = cookieResults.Values["GridSettings"];
RadGrid grid = (RadGrid)FindControl(gridId);
GridSettingsPersister LoadPersister = new GridSettingsPersister(grid);
LoadPersister.LoadSettings(settings);
grid.Rebind();
}
}
catch (Exception exception)
{
Logger.Write(exception);
}
}
private void FindFormControls(List<Control> foundSofar, Control parent)
{
List<Type> types = new List<Type> { typeof(TextBox), typeof(DropDownList), typeof(RadioButton), typeof(CheckBox), typeof(HiddenField) };
foreach (Control control in parent.Controls)
{
if (types.Any(item => item == control.GetType()))
{
foundSofar.Add(control);
}
if (control.Controls.Count > 0)
{
this.FindFormControls(foundSofar, control); // Use recursion to find all descendants.
}
}
}

How to get values from Gridview column

I have an editable GridView that emails it's content to all companies. The first row of the Gridview contains the company name (just 1 name per row). I want to email the Gridview to a specific email address based off of the company name in the first row. e.g - if first row equals companyname1 then send the email to company one; if first row equal company two, then send the email to company two. I attempted the following:
//C# - code snippet behind button
foreach (GridView item in gvCompanies.Rows)
{
if (item.SelectedRow.Cells[1].Text == "company1")
{
txtEmailAddresses.Text = "company1#gmail.com";
}
else if (item.SelectedRow.Cells[1].Text == "company2")
{
txtEmailAddresses.Text = "company2.com";
}
else if (item.SelectedRow.Cells[1].Text == "company3")
{
txtEmailAddresses.Text = "company3#aol.com";
}
else if (item.SelectedRow.Cells[1].Text == "company4")
{
txtEmailAddresses.Text = "company#aol.com";
}
}
...Could anyone provide some guidance as to what am doing wrong here?
Try Something like this...
protected void gvCompanies_SelectedIndexChanged(object sender, EventArgs e)
{
//for (int i = 0; i < gvCompanies.Rows.Count; i++)
// {
if (gvCompanies.SelectedIndex == i)
{
String compName = gvCompanies.Rows[i].Cells[1].Text; //Gets the data cell value from the grid to string
if(compName == "company1")
{
txtEmailAddresses.Text = "company1#gmail.com";
}
else if(compName == "company2")
{
txtEmailAddresses.Text = "company2#gmail.com";
}
........and so on
}
// }
}
You need to set the folowing 2 properties of gridview.
1] AutoGenerateSelectButton="true" and
2] onselectedindexchanged="GridView1_SelectedIndexChanged".

write condition statements in a sharepoint SPListItemCollection before binding the method to asp.net repeater

My situation is like this:
I have a function that returns a value as SPListItemCollection and I bind this function to a repeater.
My problem is how can I do some conditional formatting before the return value?
SPListItemCollection GetListItems()
{
SPWeb curWeb = SPContext.Current.Site.RootWeb;
string siteUrl = SPContext.Current.Web.Url;
SPListItemCollection curItems = GetDep(ListName, department);
// write condition here so that it checks if the item count is higher or
//lower than a specified number.
return curItems;
}
thank you for your help.
Im not 100% sure what you want to do before the return. If you only want to check if the resultItem.Count is bigger then 100 for example, you can do this:
SPListItemCollection GetListItems()
{
SPWeb curWeb = SPContext.Current.Site.RootWeb;
string siteUrl = SPContext.Current.Web.Url;
SPListItemCollection curItems = GetDep(ListName, department);
if (curItems.Count > 100)
{
// change the items or do whatever you want. after that, return:
foreach(SPListItem item in curItems)
{
//format/change
}
return curItems;
}
// return, without any changes
return curItems;
}
Try smth like
SPListItemCollection GetListItems()
{
SPWeb curWeb = SPContext.Current.Site.RootWeb;
string siteUrl = SPContext.Current.Web.Url;
SPListItemCollection curItems = GetDep(ListName, department);
var itemsForDepartment = curItems.GetDataTable().Rows.Where(r => r["Department"] == department); // you can try to do this is caml too
if(itemsForDepartment.Count > itemCount) {
// insert the "show me more" link
}
var itemsForDepartment = itemsForDepartment.Take(itemCount);
// bind itemsForDepartment to a Repeater
return curItems;
}
I have not compiled this code so you will have to correct some syntax mistakes ;)

How to know which value items where selected from a CheckBoxList using Request.Form?

How to get which value items where selected from a CheckBoxList using Request.Form?
I see these 2 form keys:
[12]: "ctl00$MainContent$cblTimeOfDay$0"
[13]: "ctl00$MainContent$cblTimeOfDay$3"
0 and 3 are the selected values from my check box list which has 4 items.
I'd need to find those values programmaticlaly on Page_Init
thanks,
I'm not sure about accessing these via the Request.Form. Can't you access the strongly-typed CheckBoxList control itself? This article provides a simply method that accepts a CheckBoxList and returns all the selected values; you may update this to return a reference to the selected item, or any other specifics you require:
public string[] CheckboxListSelections(System.Web.UI.WebControls.CheckBoxList list)
{
ArrayList values = new ArrayList();
for(int counter = 0; counter < list.Items.Count; counter++)
{
if(list.Items[counter].Selected)
{
values.Add(list.Items[counter].Value);
}
}
return (String[]) values.ToArray( typeof( string ) );
}
So, within your Page_Init event handler, call like so:
var selectedValues = CheckboxListSelections(myCheckBoxList);
Where myCheckBoxList is a reference to your CheckBoxList control.
I wrote this method which works but not with the best performance:
public static TimeOfDay Create(NameValueCollection httpRequestForm, string checkBoxId)
{
var result = new TimeOfDay();
var selectedCheckBoxItems = from key in httpRequestForm.AllKeys
where key.Contains(checkBoxId)
select httpRequestForm.Get(key);
if (selectedCheckBoxItems.Count() == 0)
{
result.ShowFull = true;
return result;
}
foreach (var item in selectedCheckBoxItems)
{
var selectedValue = int.Parse(item.Substring(item.Length));
switch (selectedValue)
{
case 0:
result.ShowAm = true;
break;
case 1:
result.ShowPm = true;
break;
case 2:
result.ShowEvening = true;
break;
case 3:
result.ShowFull = true;
break;
default:
throw new ApplicationException("value is not supported int the check box list.");
}
}
return result;
}
and use it like this:
TimeOfDay.Create(this.Request.Form, this.cblTimeOfDay.ID)

How to Find Control in Datalist1?

Hi can anybody tell how i can find a DataList which is inside the DataList control?Its giving the Error Object not set to an Instance.
i am finding the control this way :
DataList dl =((DataList) (DataList1.FindControl("DataList2")));
is it the right way?
It depends when you want to find the control and which control. If you just want to get all of them you loop through the DataList Items like below. Say you want to access a CheckBox inside a DataList.
foreach (DataListItem item in DataList1.Items)
{
if (item.ItemType == ListItemType.Item ||item.ItemType == ListItemType.AlternatingItem)
{
CheckBox chb=(CheckBox) item.FindControl("CheckBox1");
if (chb!= null)
{
//you can access chb.Checked value
}
}
}
Is DataList2 directly inside DataList1 or is it inside a child component of DataList1?
The FindControl method does not do a deep search for controls.
I wrote a method to do this a while ago, I'll post it here incase it's of use:
public static IEnumerable<Control>
GetDeepControlsByType<T>(this Control control)
{
foreach(Control c in control.Controls)
{
if (c is T)
{
yield return c;
}
if(c.Controls.Count > 0)
{
foreach (var x in c.GetDeepControlsByType<T>())
{
yield return x;
}
}
}
}

Resources