So I have a search page with multiple checkboxlist, 7 in total, a button to submit the search as well as a button to toggle view of all the checkbox list search parameters.
Each checkbox list has multiple checkbox options. See procedure below to understand the flow and what I am trying to accomplish.
Pages Involved:
Page A = Search Page
Page B = Equipment Details Page
Procedure:
Users navigates to search page (Page A)
Users deselects appropriate checkboxe(s) within respective checkbox list (Check boxes are already checked upon arriving at page as set by the code "selected="True"")
User clicks search button
A list of items is displayed on the same page
user clicks particular item/part they are then forwarded to the parts detail page. (Page B)
Dilemma: When a user clicks the back button after visiting the parts details page they have to, again, deselect the checkboxe(s) they want to exclude from the search results and hit the search button again to generate the desired results.
What I would like to happen is when a user clicks the back button (this is a simple button I created with an event handler) they'll be redirected back to the search page (Page A) with their selection of checkboxes auto populated and the results shown.
I have tried to implement a solution using session variables. I believe I am saving the variables (checkboxes) inside of a session variable , correctly although it is only targeting one checkbox list at the moment.
I am unsure how to complete the solution. I understand I need to cast the list back on it self, but I am unsure how to do that and where I should place the code.
Any help is welcomed. Please treat me like a noob when explaining things as I want to be sure I gain the most knowledge from this post in hopes others will be able to use this post as a reference.
Here is a sample of 1 of the checkbox list on search page (Page A):
My Code Declaring Session Variable on search page code behind (Page A) Does this look correct? It is supposed to add any checkbox which is selected to a session variable.
(There is also a bunch of other code within the submit button function which builds a query via stringbuilder, not sure if that has anything to do with what I am trying to accomplish.):
protected void Submit_Click(object sender, EventArgs e)
{
List<string> selections = new List<string>();
foreach (ListItem listItem in Equipment_Fields.Items)
{
if (listItem.Selected)
{
selections.Add(listItem.Value);
}
}
Session["selections"] = selections;
}
On Page B----Button Event
This is not working as when I click the button it just refreshes the current page without redirecting the user to the referring page. The prevPage function just stores the referrer url.
if (Session["selections"] != null)
{
List<ListItem> name = (List<ListItem>)Session["selections"];
foreach (ListItem li in name)
{
Response.Write(li);
}
Response.Redirect(prevPage);
}
Thank You for answering my post. Your feeback is greatly appreciate.
However I am unsure how to complete the solutions. Specifically for the foreach section. What should I put in this section to ensure the checkboxes are checked. Sorry I am completely new to C# and Asp.Net.
Am I supposed to do something like this.
if (Session["selections"] != null)
{
var selections = Session["selections"] as List<string>;
foreach (var selection in selections)
{
// Do something here.
}
}
It depends on how you are actually wanting to output them.
Based on your previously provided logic, it looks like only the checkboxes that were actually selected are going to be stored within your Session, so you know that those will be checked. So as mentioned in your dilemma:
coderPoet
Dilemma: When a user clicks the back button after visiting the parts details page they have to, again, deselect the checkboxe(s) they want to exclude from the search results and hit the search button again to generate the desired results.
You would basically check for the Session value within your Page_Load event and iterate through your CheckBox list and check the values that were present in the Session :
if(Session["selection"] != null)
{
// Get your selected items
var selectedItems = Session["selection"] as List<string>;
foreach (ListItem listItem in Equipment_Fields.Items)
{
// Select this item if it is present
listItem.Selected = selectedItems.Contains(listItem.Value))
}
}
I added your code to the page _load event and it still isn't working. Here is the entire code behind page, just so you can see how I have it On page A: Also Should all of the code go in the code behind on Page A or am I supposed to put it in the page_load
event for page B:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls;
using NPOI.HSSF.UserModel;
using NPOI.HSSF.Util;
using NPOI.SS.UserModel;
using Telerik.Web.UI;
using System.Data;
using System.Web.UI;
public partial class AdvancedSearch : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Session["selection"] != null)
{
// Get your selected items
var selectedItems = Session["selection"] as List<string>;
foreach (ListItem listItem in Equipment_Fields.Items)
{
// Select this item if it is present
listItem.Selected = selectedItems.Contains(listItem.Value);
}
}
if (!IsPostBack)
{
Master.SelItem = "Advanced Search";
Master.SetTitle("Advanced Search");
Results.Visible = true;
}
}
protected void Submit_Click(object sender, EventArgs e)
{
List<string> selections = new List<string>();
foreach (ListItem listItem in Equipment_Fields.Items)
{
if (listItem.Selected)
{
selections.Add(listItem.Value);
}
}
Session["selections"] = selections;
string searchValue = SearchValue.Text.Trim();
string errorMessage = string.Empty;
Results.Visible = false;
bool searchEquipment = GiTools.UI.Controls.CheckBoxList.GetCheckedItemsCount(Equipment_Fields) + GiTools.UI.Controls.CheckBoxList.GetCheckedItemsCount(Equipment_Type) + GiTools.UI.Controls.CheckBoxList.GetCheckedItemsCount(Equipment_Status) > 0;
bool searchHistory = GiTools.UI.Controls.CheckBoxList.GetCheckedItemsCount(History_Fields) + GiTools.UI.Controls.CheckBoxList.GetCheckedItemsCount(History_Status) > 0;
bool searchOTR = GiTools.UI.Controls.CheckBoxList.GetCheckedItemsCount(OTR_Fields) + GiTools.UI.Controls.CheckBoxList.GetCheckedItemsCount(OTR_Classification) > 0;
if (searchEquipment == false && searchHistory == false && searchOTR == false)
{
errorMessage += "There's no field to be searched selected.<br/>";
}
if (searchEquipment)
{
if (GiTools.UI.Controls.CheckBoxList.GetCheckedItemsCount(Equipment_Type) == 0)
{
errorMessage += "There's no <strong>Equipment Type</strong> to be searched selected.<br/>";
}
if (GiTools.UI.Controls.CheckBoxList.GetCheckedItemsCount(Equipment_Status) == 0)
{
errorMessage += "There's no <strong>Equipment Status</strong> to be searched selected.<br/>";
}
}
if (searchHistory)
{
if (GiTools.UI.Controls.CheckBoxList.GetCheckedItemsCount(History_Status) == 0)
{
errorMessage += "There's no <strong>History Status</strong> to be searched selected.<br/>";
}
}
if (searchOTR)
{
if (GiTools.UI.Controls.CheckBoxList.GetCheckedItemsCount(OTR_Classification) == 0)
{
errorMessage += "There's no <strong>OTR Classification</strong> to be searched selected.<br/>";
}
}
if (!string.IsNullOrEmpty(errorMessage))
{
GiTools.Telerik.RadWindow.RadError(Master.WindowManager_Error, errorMessage);
ShowHideSearchOptions.Text = "Hide Search Options";
Search_Options_Container.Style.Add("display", "");
}
else
{
Results.Visible = true;
Results.Rebind();
ShowHideSearchOptions.Text = "Show Search Options";
Search_Options_Container.Style.Add("display", "none");
}
if (Filter_By_Date.Checked)
{
Date_Start.Enabled = Date_End.Enabled = true;
}
else
{
Date_Start.Enabled = Date_End.Enabled = false;
}
}
private string GetSearchQuery()
{
string searchValue = SearchValue.Text.Trim();
StringBuilder queryString = new StringBuilder();
bool searchEquipment = GiTools.UI.Controls.CheckBoxList.GetCheckedItemsCount(Equipment_Fields) + GiTools.UI.Controls.CheckBoxList.GetCheckedItemsCount(Equipment_Type) + GiTools.UI.Controls.CheckBoxList.GetCheckedItemsCount(Equipment_Status) > 0;
bool searchHistory = GiTools.UI.Controls.CheckBoxList.GetCheckedItemsCount(History_Fields) + GiTools.UI.Controls.CheckBoxList.GetCheckedItemsCount(History_Status) > 0;
bool searchOTR = GiTools.UI.Controls.CheckBoxList.GetCheckedItemsCount(OTR_Fields) + GiTools.UI.Controls.CheckBoxList.GetCheckedItemsCount(OTR_Classification) > 0;
if (searchEquipment)
{
queryString.Append("SELECT equipment.equipment_id, equipment.equipment_id AS id, CAST(equipment.tms_num as varchar(30)) AS id_label, LEN(equipment.tms_num) AS id_label_length, 'Equipment' AS type, equipment.description AS description FROM equipment WHERE 1=1");
if (!string.IsNullOrEmpty(searchValue) && GiTools.UI.Controls.CheckBoxList.GetCheckedItemsCount(Equipment_Fields) > 0)
{
StringBuilder whereClause = new StringBuilder(" AND (1=2");
if (Equipment_Fields.Items.FindByValue("TMS #").Selected) whereClause.Append(string.Format(" OR equipment.tms_num LIKE '{0}'", searchValue));
if (Equipment_Fields.Items.FindByValue("Assigned To").Selected) whereClause.Append(string.Format(" OR equipment.assigned_to LIKE '{0}'", searchValue));
if (Equipment_Fields.Items.FindByValue("Issued To").Selected) whereClause.Append(string.Format(" OR equipment.issued_to LIKE '{0}'", searchValue));
if (Equipment_Fields.Items.FindByValue("Department").Selected) whereClause.Append(string.Format(" OR equipment.department LIKE '{0}'", searchValue));
if (Equipment_Fields.Items.FindByValue("Manufacturer").Selected) whereClause.Append(string.Format(" OR equipment.manufacturer LIKE '{0}'", searchValue));
if (Equipment_Fields.Items.FindByValue("Model #").Selected) whereClause.Append(string.Format(" OR equipment.model_num LIKE '{0}'", searchValue));
if (Equipment_Fields.Items.FindByValue("Serial #").Selected) whereClause.Append(string.Format(" OR equipment.serial_num LIKE '{0}'", searchValue));
if (Equipment_Fields.Items.FindByValue("Description").Selected) whereClause.Append(string.Format(" OR equipment.description LIKE '{0}'", searchValue));
if (Equipment_Fields.Items.FindByValue("Characteristics").Selected) whereClause.Append(string.Format(" OR equipment.characteristics LIKE '{0}'", searchValue));
if (Equipment_Fields.Items.FindByValue("Calibration Procedure").Selected) whereClause.Append(string.Format(" OR equipment.calibration_procedure LIKE '{0}'", searchValue));
if (Equipment_Fields.Items.FindByValue("Calibration Standard").Selected) whereClause.Append(string.Format(" OR equipment.calibration_standard LIKE '{0}'", searchValue));
if (Equipment_Fields.Items.FindByValue("Calibration Interval").Selected) whereClause.Append(string.Format(" OR equipment.calibration_interval LIKE '{0}'", searchValue));
if (Equipment_Fields.Items.FindByValue("Required Accuracy").Selected) whereClause.Append(string.Format(" OR equipment.required_accuracy LIKE '{0}'", searchValue));
whereClause.Append(")");
queryString.Append(whereClause.ToString());
}
if (GiTools.UI.Controls.CheckBoxList.GetCheckedItemsCount(Equipment_Type) == 1)
{
queryString.Append(string.Format(" AND equipment.type = {0}", Equipment_Type.SelectedValue));
}
if (GiTools.UI.Controls.CheckBoxList.GetCheckedItemsCount(Equipment_Status) < Equipment_Status.Items.Count)
{
queryString.Append(string.Format(" AND equipment.status IN ({0})", string.Join(",", GiTools.UI.Controls.CheckBoxList.GetCheckedItemsValues(Equipment_Status).ToArray())));
}
if (!Equipment_Status_Obsolete.Items.FindByValue("Include Obsolete").Selected)
{
queryString.Append(" AND equipment.is_obsolete = 0");
}
if (Filter_By_Date.Checked)
{
if (Date_Start.SelectedDate.HasValue)
{
queryString.Append(" AND equipment.date_submitted >= '" + Date_Start.SelectedDate.Value.Date + "'");
}
if (Date_End.SelectedDate.HasValue)
{
queryString.Append(" AND equipment.date_submitted <= '" + Date_End.SelectedDate.Value.Date.AddDays(1).AddMilliseconds(-1) + "'");
}
if (Date_Start.SelectedDate.HasValue)
{
queryString.Append(" AND equipment.date_submitted >= '" + Date_Start.SelectedDate.Value.Date + "'");
}
if (Date_End.SelectedDate.HasValue)
{
queryString.Append(" AND equipment.date_submitted <= '" + Date_End.SelectedDate.Value.Date.AddDays(1).AddMilliseconds(-1) + "'");
}
}
}
if (searchHistory)
{
if (queryString.Length > 0)
{
queryString.Append(" UNION ALL ");
}
queryString.Append("SELECT equipment.equipment_id, history_id AS id, CAST(history_id as varchar(30)) AS id_label, LEN(history_id) AS id_label_length, 'History' AS type, 'TMS # ' + equipment.tms_num + ': ' + history.remarks AS description FROM history INNER JOIN equipment ON history.equipment_id = equipment.equipment_id WHERE 1=1");
if (!string.IsNullOrEmpty(searchValue) && GiTools.UI.Controls.CheckBoxList.GetCheckedItemsCount(History_Fields) > 0)
{
StringBuilder whereClause = new StringBuilder(" AND (1=2");
if (History_Fields.Items.FindByValue("ID Number").Selected) whereClause.Append(string.Format(" OR history.history_id LIKE '{0}'", searchValue));
if (History_Fields.Items.FindByValue("Inspector").Selected) whereClause.Append(string.Format(" OR history.inspector LIKE '{0}'", searchValue));
if (History_Fields.Items.FindByValue("Inspector E-mail").Selected) whereClause.Append(string.Format(" OR history.inspector_email LIKE '{0}'", searchValue));
if (History_Fields.Items.FindByValue("Remarks").Selected) whereClause.Append(string.Format(" OR history.remarks LIKE '{0}'", searchValue));
whereClause.Append(")");
queryString.Append(whereClause.ToString());
}
if (GiTools.UI.Controls.CheckBoxList.GetCheckedItemsCount(History_Status) < History_Status.Items.Count)
{
queryString.Append(string.Format(" AND history.status IN ({0})", string.Join(",", GiTools.UI.Controls.CheckBoxList.GetCheckedItemsValues(History_Status).ToArray())));
}
if (Filter_By_Date.Checked)
{
if (Date_Start.SelectedDate.HasValue)
{
queryString.Append(" AND history.date_submitted >= '" + Date_Start.SelectedDate.Value.Date + "'");
}
if (Date_End.SelectedDate.HasValue)
{
queryString.Append(" AND history.date_submitted <= '" + Date_End.SelectedDate.Value.Date.AddDays(1).AddMilliseconds(-1) + "'");
}
if (Date_Start.SelectedDate.HasValue)
{
queryString.Append(" AND history.date_submitted >= '" + Date_Start.SelectedDate.Value.Date + "'");
}
if (Date_End.SelectedDate.HasValue)
{
queryString.Append(" AND history.date_submitted <= '" + Date_End.SelectedDate.Value.Date.AddDays(1).AddMilliseconds(-1) + "'");
}
}
}
if (searchOTR)
{
if (queryString.Length > 0)
{
queryString.Append(" UNION ALL ");
}
queryString.Append("SELECT equipment.equipment_id, otr_id AS id, CAST(otr_id as varchar(30)) AS id_label, LEN(otr_id) AS id_label_length, 'OTR' AS type, 'TMS # ' + equipment.tms_num + ': ' + otr.submitter_comments AS description FROM otr INNER JOIN equipment ON otr.equipment_id = equipment.equipment_id WHERE 1=1");
if (!string.IsNullOrEmpty(searchValue) && GiTools.UI.Controls.CheckBoxList.GetCheckedItemsCount(OTR_Fields) > 0)
{
StringBuilder whereClause = new StringBuilder(" AND (1=2");
if (OTR_Fields.Items.FindByValue("ID Number").Selected) whereClause.Append(string.Format(" OR otr.otr_id LIKE '{0}'", searchValue));
if (OTR_Fields.Items.FindByValue("Submitter").Selected) whereClause.Append(string.Format(" OR otr.submitted_by LIKE '{0}'", searchValue));
if (OTR_Fields.Items.FindByValue("Submitter E-mail").Selected) whereClause.Append(string.Format(" OR otr.submitted_by_email LIKE '{0}'", searchValue));
if (OTR_Fields.Items.FindByValue("Actual accuracy").Selected) whereClause.Append(string.Format(" OR otr.actual_accuracy LIKE '{0}'", searchValue));
whereClause.Append(")");
queryString.Append(whereClause.ToString());
}
if (searchOTR && GiTools.UI.Controls.CheckBoxList.GetCheckedItemsCount(OTR_Classification) == 1)
{
queryString.Append(string.Format(" AND otr.classification = {0}", OTR_Classification.SelectedValue));
}
if (Filter_By_Date.Checked)
{
if (Date_Start.SelectedDate.HasValue)
{
queryString.Append(" AND otr.date_submitted >= '" + Date_Start.SelectedDate.Value.Date + "'");
}
if (Date_End.SelectedDate.HasValue)
{
queryString.Append(" AND otr.date_submitted <= '" + Date_End.SelectedDate.Value.Date.AddDays(1).AddMilliseconds(-1) + "'");
}
if (Date_Start.SelectedDate.HasValue)
{
queryString.Append(" AND otr.date_submitted >= '" + Date_Start.SelectedDate.Value.Date + "'");
}
if (Date_End.SelectedDate.HasValue)
{
queryString.Append(" AND otr.date_submitted <= '" + Date_End.SelectedDate.Value.Date.AddDays(1).AddMilliseconds(-1) + "'");
}
}
}
queryString.Append(" ORDER BY type, id_label_length, id_label");
return queryString.ToString();
}
protected void Results_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
{
Results.DataSource = GiTools.Database.MsSql.SqlToDataTable(Common.ConnectionString, GetSearchQuery());
}
protected void Results_ItemDataBound(object sender, GridItemEventArgs e)
{
if (e.Item is GridPagerItem)
{
GridPagerItem pager = (GridPagerItem)e.Item;
Label lbl = (Label)pager.FindControl("ChangePageSizeLabel");
lbl.Visible = false;
RadComboBox combo = (RadComboBox)pager.FindControl("PageSizeComboBox");
combo.Visible = false;
}
if (e.Item is GridDataItem)
{
string type = DataBinder.Eval(e.Item.DataItem, "type", string.Empty);
if (type == "OTR")
{
e.Item.Cells[2].Text = string.Format("<a href='OtrView.aspx?id={0}'>{0}</a>", DataBinder.Eval(e.Item.DataItem, "id", string.Empty));
}
else if (type == "History")
{
e.Item.Cells[2].Text = string.Format("<a href='EquipmentView.aspx?id={0}'>{1}</a>", DataBinder.Eval(e.Item.DataItem, "equipment_id", string.Empty), DataBinder.Eval(e.Item.DataItem, "id", string.Empty));
}
else if (type == "Equipment")
{
e.Item.Cells[2].Text = string.Format("<a href='EquipmentView.aspx?id={0}'>{1}</a>", DataBinder.Eval(e.Item.DataItem, "equipment_id", string.Empty), DataBinder.Eval(e.Item.DataItem, "id_label", string.Empty));
}
}
}
protected void DataDump_Click(object sender, EventArgs e)
{
DataClassesDataContext dc = new DataClassesDataContext();
DataTable dt = GiTools.Database.MsSql.SqlToDataTable(Common.ConnectionString, GetSearchQuery());
HSSFWorkbook hssfworkbook = new HSSFWorkbook();
HSSFSheet sheet = (HSSFSheet)hssfworkbook.CreateSheet("Sheet1");
int rowIndex = 0;
int columnIndex = 0;
#region add table headers
HSSFFont boldFont = (HSSFFont)hssfworkbook.CreateFont();
boldFont.Color = HSSFColor.BLACK.index;
boldFont.Boldweight = (short)FontBoldWeight.BOLD;
HSSFCellStyle header_Bold = (HSSFCellStyle)hssfworkbook.CreateCellStyle();
header_Bold.SetFont(boldFont);
HSSFRow dataRow = (HSSFRow)sheet.CreateRow(rowIndex);
dataRow.CreateCell(columnIndex++).SetCellValue("ID #");
dataRow.CreateCell(columnIndex++).SetCellValue("Type");
dataRow.CreateCell(columnIndex++).SetCellValue("Description");
for (int i = 0; i < sheet.GetRow(0).LastCellNum; i++)
{
HSSFCell cell = (HSSFCell)sheet.GetRow(0).GetCell(i);
cell.CellStyle = header_Bold;
}
#endregion
#region add data
foreach (DataRow row in dt.Rows)
{
rowIndex++;
columnIndex = 0;
dataRow = (HSSFRow)sheet.CreateRow(rowIndex);
dataRow.CreateCell(columnIndex++).SetCellValue(GiTools.DataTypes.String.TryParse(row[1]));
dataRow.CreateCell(columnIndex++).SetCellValue(GiTools.DataTypes.String.TryParse(row[2]));
dataRow.CreateCell(columnIndex++).SetCellValue(GiTools.DataTypes.String.TryParse(row[3]));
}
#endregion
// autosize all columns
for (int i = 0; i < sheet.GetRow(0).LastCellNum; i++)
{
if (i != 12 && i != 23)
{
sheet.AutoSizeColumn(i);
}
}
//Write the stream data of workbook to the root directory
string fileName = "~/Downloads/Advanced-Search-Result.xls";
FileStream file = new FileStream(Server.MapPath(fileName), FileMode.Create);
hssfworkbook.Write(file);
file.Close();
GiTools.UI.Page.DownloadFile(this, fileName, true);
}
}
if (Session["selection"] != null) { // Get your selected items var selectedItems = Session["selection"] as List<string>; foreach (ListItem listItem in Equipment_Fields.Items) { // Select this item if it is present listItem.Selected = selectedItems.Contains(listItem.Value);
} }
coderPoet
protected void Submit_Click(object sender, EventArgs e) { List<string> selections = new List<string>(); foreach (ListItem listItem in Equipment_Fields.Items) { if (listItem.Selected) { selections.Add(listItem.Value); } }
Session["selections"] = selections;
According to your code, I find the session name is different, so you should modify your code to ensure that the name of the session is the same.
One other question, I have about 7 checkbox list, how do I include the other 6 checkbox list inside the session variable?
You could store them the same way, although the easiest way to handle this would be to use some type of Dictionary so that you could associate the appropriate ID of your CheckBoxList with the List itself :
// Build your Dictionary
Dictionary<string,CheckBoxList> checkBoxLists = new Dictionary<string,CheckBoxList>();
// Add each of your CheckBoxes along with their IDs to the Dictionary
checkBoxLists.Add(YourCheckBoxList.ClientID, YourCheckBoxList);
// Repeat for each of your CheckBoxes here
// Store the Dictionary in the Session
Session["selections"] = checkBoxLists;
Then when you return to the Page, you would likely want to do the following :
Check to ensure your Session value exists.
If it does, loop through all of your existing CheckBoxList controls on your current page.
Within the loop, if one of them exists in the Session, then check the appropriate elements
You can see an example of what this might look like below :
// Check if your Session value exists
if(Session["selections"] != null)
{
// If it does, cast it
var checkBoxes = Session["selections"] as Dictionary<string,CheckBoxList>;
// If the cast was successful, iterate through all of your current CheckBoxList elements
foreach (CheckBoxList cbl in Controls.OfType<CheckBoxList>())
{
// If the current check box list is in your Session, update it's checked values
if(checkBoxes.ContainsKey(cbl.ClientID))
{
// It does exist, so update the items accordingly
for(var c = 0; c < cbl.Items.Count(); c++)
{
// Update this item to match the one from the Session
cbl.Items[c].Selected = checkBoxes[cbl.ClientID].Items[c].Selected;
}
}
}
}
Sorry for the delayed response, it's been really busy lately. Your code makes perfect sense. I really appreciate all your help. Thank you for the programming lesson. Maybe you can help me with something else. I'll start a new thread.
Member
13 Points
24 Posts
Casting Back Session Variables C# Asp.net Multiple Checkbox List
Sep 24, 2015 11:36 AM|coderPoet|LINK
So I have a search page with multiple checkboxlist, 7 in total, a button to submit the search as well as a button to toggle view of all the checkbox list search parameters.
Each checkbox list has multiple checkbox options. See procedure below to understand the flow and what I am trying to accomplish.
Pages Involved:
Page A = Search Page
Page B = Equipment Details Page
Procedure:
Users navigates to search page (Page A)
Users deselects appropriate checkboxe(s) within respective checkbox list (Check boxes are already checked upon arriving at page as set by the code "selected="True"")
User clicks search button
A list of items is displayed on the same page
user clicks particular item/part they are then forwarded to the parts detail page. (Page B)
Dilemma: When a user clicks the back button after visiting the parts details page they have to, again, deselect the checkboxe(s) they want to exclude from the search results and hit the search button again to generate the desired results.
What I would like to happen is when a user clicks the back button (this is a simple button I created with an event handler) they'll be redirected back to the search page (Page A) with their selection of checkboxes auto populated and the results shown.
I have tried to implement a solution using session variables. I believe I am saving the variables (checkboxes) inside of a session variable , correctly although it is only targeting one checkbox list at the moment.
I am unsure how to complete the solution. I understand I need to cast the list back on it self, but I am unsure how to do that and where I should place the code.
Any help is welcomed. Please treat me like a noob when explaining things as I want to be sure I gain the most knowledge from this post in hopes others will be able to use this post as a reference.
Here is a sample of 1 of the checkbox list on search page (Page A):
My Code Declaring Session Variable on search page code behind (Page A) Does this look correct? It is supposed to add any checkbox which is selected to a session variable.
(There is also a bunch of other code within the submit button function which builds a query via stringbuilder, not sure if that has anything to do with what I am trying to accomplish.):
On Page B----Button Event
This is not working as when I click the button it just refreshes the current page without redirecting the user to the referring page. The prevPage function just stores the referrer url.
asp.net Session csharp
All-Star
114593 Points
18503 Posts
MVP
Re: Casting Back Session Variables C# Asp.net Multiple Checkbox List
Sep 24, 2015 11:45 AM|Rion Williams|LINK
Since you are currently storing your collection as a List<string> in your Session, you would need to cast it the same way to retrieve it :
Then you could simply loop through it using a foreach loop :
asp.net Session csharp
Member
13 Points
24 Posts
Re: Casting Back Session Variables C# Asp.net Multiple Checkbox List
Sep 24, 2015 11:53 AM|coderPoet|LINK
Hi Rion,
Thank You for answering my post. Your feeback is greatly appreciate.
However I am unsure how to complete the solutions. Specifically for the foreach section. What should I put in this section to ensure the checkboxes are checked. Sorry I am completely new to C# and Asp.Net.
Am I supposed to do something like this.
asp.net Session csharp
All-Star
114593 Points
18503 Posts
MVP
Re: Casting Back Session Variables C# Asp.net Multiple Checkbox List
Sep 24, 2015 12:37 PM|Rion Williams|LINK
It depends on how you are actually wanting to output them.
Based on your previously provided logic, it looks like only the checkboxes that were actually selected are going to be stored within your Session, so you know that those will be checked. So as mentioned in your dilemma:
You would basically check for the Session value within your Page_Load event and iterate through your CheckBox list and check the values that were present in the Session :
asp.net Session csharp
Member
13 Points
24 Posts
Re: Casting Back Session Variables C# Asp.net Multiple Checkbox List
Sep 24, 2015 01:26 PM|coderPoet|LINK
I added your code to the page _load event and it still isn't working. Here is the entire code behind page, just so you can see how I have it On page A: Also Should all of the code go in the code behind on Page A or am I supposed to put it in the page_load event for page B:
asp.net Session csharp
Star
8460 Points
1445 Posts
Re: Casting Back Session Variables C# Asp.net Multiple Checkbox List
Sep 29, 2015 03:35 AM|Klein Zhang|LINK
Hi coderPoet
According to your code, I find the session name is different, so you should modify your code to ensure that the name of the session is the same.
Best Regards,
Klein zhang
asp.net Session csharp
Member
13 Points
24 Posts
Re: Casting Back Session Variables C# Asp.net Multiple Checkbox List
Sep 29, 2015 04:39 PM|coderPoet|LINK
Thank You very much. I'm not sure how I let that slip by me. I appreciate you taking the time out to correct my error.
asp.net Session csharp
Member
13 Points
24 Posts
Re: Casting Back Session Variables C# Asp.net Multiple Checkbox List
Sep 29, 2015 04:42 PM|coderPoet|LINK
One other question, I have about 7 checkbox list, how do I include the other 6 checkbox list inside the session variable?
asp.net Session csharp
All-Star
114593 Points
18503 Posts
MVP
Re: Casting Back Session Variables C# Asp.net Multiple Checkbox List
Sep 29, 2015 05:29 PM|Rion Williams|LINK
You could store them the same way, although the easiest way to handle this would be to use some type of Dictionary so that you could associate the appropriate ID of your CheckBoxList with the List itself :
Then when you return to the Page, you would likely want to do the following :
You can see an example of what this might look like below :
Does that make sense?
asp.net Session csharp
Member
13 Points
24 Posts
Re: Casting Back Session Variables C# Asp.net Multiple Checkbox List
Oct 22, 2015 09:44 AM|coderPoet|LINK
Sorry for the delayed response, it's been really busy lately. Your code makes perfect sense. I really appreciate all your help. Thank you for the programming lesson. Maybe you can help me with something else. I'll start a new thread.
asp.net Session csharp