I am trying to get the items stored in a sessions variable into a repeater for users to see. However, I am not entirely sure how to do it (I'm new to session variables). Basically, when users enter in quantities for items on once page the hit submit, they are taken to an "order summary" page, which will display what they plan to purchase. I have successfully set up a session variable to contain the sku and quantity of each product the user selects, but I do not know how to get the information out.
I've stored the information in the session variable as [sku],[quantity];[sku],[quantity];[sku],[quantity] and so on. I figure I must do a split or something based on the commas and semicolons but I am not sure how to do so with a session variable.
The code for the product listing page that contains the information to be stored in the session variable:
public partial class GojoptproductlistSublayout : System.Web.UI.UserControl
{
private void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
Item CurrentItem = Sitecore.Context.Item;
Item HomeItem = ScHelper.FindAncestor(CurrentItem, "gojoMarket");
if (HomeItem != null)
{
Item ProductGroup = HomeItem.Axes.SelectSingleItem(#"child::*[##templatename='gojoMarketOfficeBuildigProductMap']/*[##templatename='gojoProductList']");
if (ProductGroup != null)
{
Item[] LocationList = ProductGroup.Axes.SelectItems(#"child::*[##templatename='gojoProductLocation' and #Active = '1']");
if (LocationList != null)
{
DataSet ds = new DataSet();
DataTable locations = ds.Tables.Add("locations");
locations.Columns.Add("LocationName", Type.GetType("System.String"));
locations.Columns.Add("LocationID", Type.GetType("System.String"));
foreach (Item LocationItem in LocationList)
{
DataRow dr = locations.NewRow();
dr["LocationName"] = LocationItem.Fields["Header"].Value;
dr["LocationID"] = LocationItem.ID.ToString();
locations.Rows.Add(dr);
}
locationRepeater.DataSource = ds;
locationRepeater.DataMember = "locations";
locationRepeater.DataBind();
}
}
}
}
}
protected void SetInner(object sender, RepeaterItemEventArgs e)
{
if ((e.Item.ItemType != ListItemType.Footer) & (e.Item.ItemType != ListItemType.Header))
{
Label refID = (Label)e.Item.FindControl("refID");
Label test = (Label)e.Item.FindControl("test");
Repeater areaRepeater = (Repeater)e.Item.FindControl("areaRepeater");
Database db = Sitecore.Context.Database;
Item LocationAreaItem = db.Items[refID.Text];
if (LocationAreaItem != null)
{
Item[] AreaList = LocationAreaItem.Axes.SelectItems(#"child::*[##templatename='gojoProductLocationArea' and #Active = '1']");
if (AreaList != null)
{
DataSet dset = new DataSet();
DataTable areas = dset.Tables.Add("areas");
areas.Columns.Add("AreaName", Type.GetType("System.String"));
areas.Columns.Add("Sku", Type.GetType("System.String"));
areas.Columns.Add("ProductName", Type.GetType("System.String"));
areas.Columns.Add("masterSku", Type.GetType("System.String"));
areas.Columns.Add("masterName", Type.GetType("System.String"));
areas.Columns.Add("Size", Type.GetType("System.String"));
areas.Columns.Add("SkuID", Type.GetType("System.String"));
areas.Columns.Add("AreaID",Type.GetType("System.String"));
areas.Columns.Add("productID", Type.GetType("System.String"));
foreach (Item AreaItem in AreaList)
{
DataRow drow = areas.NewRow();
drow["AreaName"] = AreaItem.Fields["Header"].Value;
drow["AreaID"] = AreaItem.ID.ToString();
areas.Rows.Add(drow);
Item[] SkuList = AreaItem.Axes.SelectItems(#"child::*[(##templatename='gojoPTRefill' or ##templatename = 'gojoPTAccessories' or ##templatename = 'gojoPTDispenser' or ##templatename = 'gojoPTSelfDispensed') and #Active = '1']");
foreach (Item ChildItem in SkuList)
{
Item MarketProduct = db.Items[ChildItem.Fields["Reference SKU"].Value];
drow["productID"] = ChildItem.ID.ToString();
if (MarketProduct != null)
{
Item MasterProduct = db.Items[MarketProduct.Fields["Master Product"].Value];
if (MasterProduct != null)
{
DataRow newRow = areas.NewRow();
if(MasterProduct.TemplateName == "gojoSKUSelfDispensed" || MasterProduct.TemplateName == "gojoSKURefill")
{
newRow["Size"] = MasterProduct.Fields["Size"].Value;
}
else
{
newRow["Size"] = "-";
}
newRow["Sku"] = MasterProduct.Fields["SKU"].Value;
newRow["productID"] = MasterProduct.ID.ToString();
Item MasterProductName = db.Items[MasterProduct.Fields["Complete Product Name"].Value];
if (MasterProductName != null)
{
newRow["ProductName"] = MasterProductName.Fields["Complete Name"].Value;
}
areas.Rows.Add(newRow);
}
}
}
}
areaRepeater.DataSource = dset;
areaRepeater.DataMember = "areas";
areaRepeater.DataBind();
}
}
}
}
protected bool checkQtys(ref int ItemCnt, ref ArrayList LinesToOrder)
{
Repeater locationRepeater = (Repeater)FindControl("locationRepeater");
bool validQtys = true;
string productID = "";
int qty;
qtyErrorMsg.Text = "";
qtyErrorMsgTop.Text = "";
foreach (RepeaterItem repItem in locationRepeater.Items)
{
if (repItem != null)
{
Repeater areaRepeater = (Repeater)repItem.FindControl("areaRepeater");
if (areaRepeater != null)
{
foreach (RepeaterItem skuItm in areaRepeater.Items)
{
if (skuItm != null)
{
Label SkuID = (Label)skuItm.FindControl("SkuID");
Label qtyID = (Label)skuItm.FindControl("qtyID");
PlaceHolder inner = (PlaceHolder)skuItm.FindControl("ProductTable");
if (inner != null)
{
foreach (Control ct in inner.Controls)
{
if (ct is TextBox)
{
TextBox lineQty = (TextBox)ct;
Label prodID = (Label)inner.FindControl("productID");
if (lineQty.Text != "")
{
try
{
int.Parse(lineQty.Text);
productID = prodID.Text;
qty = int.Parse(lineQty.Text);
if (qty > 0)
{
noItemMsg.Visible = false;
noItemMsgTop.Visible = false;
ItemCnt++; //only count items with valid qty values
LinesToOrder.Add(new LineItem(productID, qty));
}
else
{//Qty is 0 or less error
validQtys = false;
qtyErrorMsg.Text = "Quantity must be a number<br />";
qtyErrorMsgTop.Text = "Quantity must be a number<br />";
}
}
catch
{//NaN - display error msg
validQtys = false;
qtyErrorMsg.Text = "Quantity must be a number<br />";
qtyErrorMsgTop.Text = "Quantity must be a number<br />";
}
}
}
}
}
}
}
}
}
}
return validQtys;
}
class LineItem
{//This class will store the product information
public string SKUID;
public int Qty;
public LineItem(string InSKUID, int InQty)
{
this.SKUID = InSKUID;
this.Qty = InQty;
}
}
protected void orderSubmit(object sender, EventArgs e)
{
int ItemCnt = 0;
bool validQtys = true;
ArrayList LinesToOrder = new ArrayList();
Label lb = FindControl("order") as Label;
if (checkQtys(ref ItemCnt,ref LinesToOrder))
{
if (ItemCnt == 0)
{//make sure at least one item with proper qty amount is entered before submitting the order
validQtys = false;
noItemMsg.Visible = true;
noItemMsg.Text = "You must order at least one item<br />";
noItemMsgTop.Visible = true;
noItemMsgTop.Text = "You must order at least one item<br />";
}
if (validQtys)
{//save the information to a session variable and send users to order review page
try
{
foreach (LineItem WorkLine in LinesToOrder)
{
lb.Text += WorkLine.SKUID + ", " + WorkLine.Qty + ";";
}
Session["orderComplete"] = lb.Text;
}
catch (Exception x)
{
Response.Write(x.Message.ToString());
}
Response.Redirect("/united-states/market/office-buildings/obproductmap/OrderReview");
}
}
}
}
Here is the designer code with the repeater that is meant to hold the order summary:
<asp:Repeater ID="orderRepeater" runat="server" >
<headertemplate>
<tr>
<th>SKU</th>
<th>Quantity</th>
</tr>
</headertemplate>
<itemtemplate>
<tr>
<td><%#Eval("sku") %></td>
<td><%#Eval("qty") %></td>
</tr>
</itemtemplate>
</asp:Repeater>
And here is the code behind:
private void Page_Load(object sender, EventArgs e)
{
Item CurrentItem = Sitecore.Context.Item;
Item HomeItem = ScHelper.FindAncestor(CurrentItem, "gojoMarket");
if (Session["orderComplete"] != "")
{
if (HomeItem != null)
{
Item ProductGroup = HomeItem.Axes.SelectSingleItem(#"child::*[##templatename='gojoMarketOfficeBuildigProductMap']/*[##templatename='gojoOrderReview']");
if (ProductGroup != null)
{
//this is where I am confused on how to proceed
}
}
}
}
Everything is working and I did a Response.Write test on the session variable to make sure it had the correct information and it did.
Thanks in advance!
Before I try to address your question, lets take a look at some basics. A Session can hold an object, not just a string object. I would change:
if (Session["orderComplete"] != "")
to
if (Session["orderComplete"] != null && Session["orderComplete"] != "")
if you don't, and Session["orderComplete"] is null, Session["orderComplete"] != "" will throw an error object not set to an instance of an object
And now to your question. Setting your session variable to [sku],[quantity];[sku],[quantity];[sku],[quantity], is not a good idea. For one, its not object oriented and 2, its not going to bind to any repeater or data source. You should create an object and bind a list of those objects to your control:
pseudo code:
class Program
{
static void Main(string[] args)
{
List<Order> orders = new List<Order>();
orders.Add(new Order { Sku = "ABC", Qty = 10});
}
}
public class Order {
public String Sku { get; set; }
public int Qty { get; set; }
}
Then you can bind orders to your repeater. For example:
if (Session["orderComplete"] != null && Session["orderComplete"] != ""){
List<Order> orders = Session["orderComplete"] as List<Order>;
myRepeater.DataSource = orders;
myRepeater.DataBind();
}
Related
I need to do a dropdownlist with optgroup.
I found lots of guides and all foresee the use of WebControlAdapter
this is the guide that I'm fllowing
I've added the class to my App_Code folder project:
namespace admin.App_Code
{
public class DropDownListAdapter :
System.Web.UI.WebControls.Adapters.WebControlAdapter
{
protected override void RenderContents(System.Web.UI.HtmlTextWriter writer)
{
// The current control being "adaptered" is available within context from the Control property
DropDownList dropDownList = (DropDownList)Control;
ListItemCollection items = dropDownList.Items;
// Retrieve Optgrouping using LinQ
var groups = (from p in items.OfType<ListItem>()
group p by p.Attributes["Group"] into g
select new { Label = g.Key, Items = g.ToList<ListItem>
() });
foreach (var group in groups)
{
if (!String.IsNullOrEmpty(group.Label))
{
writer.WriteBeginTag("optgroup");
writer.WriteAttribute("label", group.Label);
writer.Write(">");
}
int count = group.Items.Count();
if (count > 0)
{
bool flag = false;
for (int i = 0; i < count; i++)
{
ListItem item = group.Items[i];
writer.WriteBeginTag("option");
if (item.Selected)
{
if (flag)
{
throw new HttpException("Multiple selected items not allowed");
}
flag = true;
writer.WriteAttribute("selected", "selected");
}
if (!item.Enabled)
{
writer.WriteAttribute("disabled", "true");
}
writer.WriteAttribute("value", item.Value, true);
if (this.Page != null)
{
this.Page.ClientScript.RegisterForEventValidation(dropDownList.UniqueID, item.Value);
}
writer.Write('>');
HttpUtility.HtmlEncode(item.Text, writer);
writer.WriteEndTag("option");
writer.WriteLine();
}
}
if (!String.IsNullOrEmpty(group.Label))
{
writer.WriteEndTag("optgroup");
}
}
}
private Object _ViewState;
protected override void OnLoad(EventArgs e)
{
if (Page.IsPostBack)
{
if (_ViewState != null)
{
Object[] groups = (Object[])_ViewState;
DropDownList dropDownList = (DropDownList)Control;
// Add saved optgroups to ListItems
for (Int32 i = 0; i < groups.Length; i++)
{
if (groups[i] != null)
{
dropDownList.Items[i].Attributes["Group"] = groups[i].ToString();
}
}
}
}
base.OnLoad(e);
}
protected override void LoadAdapterViewState(object state)
{
// Retrieve existing state
_ViewState = state;
}
protected override object SaveAdapterViewState()
{
DropDownList dropDownList = (DropDownList)Control;
Int32 count = dropDownList.Items.Count;
Object[] values = new Object[count];
// Retrieve Optgrouping from ListItem
for (int i = 0; i < count; i++)
{
values[i] = dropDownList.Items[i].Attributes["Group"];
}
return values;
}
}
}
public static void loadDDLModelli(ref DropDownList ddl, List<dynamic>
objects)
{
Int16 cont = 0;
ddl.Items.Clear();
System.Web.UI.WebControls.ListItem li;
String idModello = "";
String nomeModello = "";
String nomeBrand = "";
String oggetto = "";
List<System.Web.UI.WebControls.ListItem> items = new List<System.Web.UI.WebControls.ListItem>();
foreach (var item in objects)
{
oggetto = item.ToString().Replace("{", "").Replace("}", "");
idModello = oggetto.Split(',')[0].Split('=')[1].Trim();
nomeModello = oggetto.Split(',')[1].Split('=')[1].Trim();
nomeBrand = oggetto.Split(',')[2].Split('=')[1].Trim();
li = new System.Web.UI.WebControls.ListItem(nomeBrand+" - "+nomeModello, idModello);
li.Attributes["Group"] = nomeBrand;
items.Add(li);
cont++;
};
ddl.DataSource = items;
ddl.DataBind();
ddl.SelectedIndex = -1;
}
I've added the folder App_Browser to my project (did not exist) and I've added the file BrowserFile.browser
<browsers>
<browser refID="Default">
<controlAdapters>
<adapter controlType="System.Web.UI.WebControls.DropDownList"
adapterType="admin.App_Code.DropDownListAdapter" />
</controlAdapters>
</browser>
</browsers>
in my page .aspx (that is in the same folder of the class DropDownListAdapter I have
<asp:DropDownList runat="server" ID="ddlModelli" CssClass="form-control multipleSelect"></asp:DropDownList>
that is filled in this way
public static void loadDDLModelli(ref DropDownList ddl, List<dynamic> objects)
{
Int16 cont = 0;
ddl.Items.Clear();
System.Web.UI.WebControls.ListItem li;
String idModello = "";
String nomeModello = "";
String nomeBrand = "";
String oggetto = "";
List<System.Web.UI.WebControls.ListItem> items = new List<System.Web.UI.WebControls.ListItem>();
foreach (var item in objects)
{
oggetto = item.ToString().Replace("{", "").Replace("}", "");
idModello = oggetto.Split(',')[0].Split('=')[1].Trim();
nomeModello = oggetto.Split(',')[1].Split('=')[1].Trim();
nomeBrand = oggetto.Split(',')[2].Split('=')[1].Trim();
li = new System.Web.UI.WebControls.ListItem(nomeBrand+" - "+nomeModello, idModello);
li.Attributes["Group"] = nomeBrand;
items.Add(li);
cont++;
};
ddl.DataSource = items;
ddl.DataBind();
ddl.SelectedIndex = -1;
}
the problem is that, when I watch the source code I do not have the optgroup tag but only options tag.
In fact, if I put a breakpoint in the first line of the method RenderContents this doesn't fire.
What I'm doing wrong?
I solved the issue.
The problem was in the method LoadDDLModelli.
Instead of setting DataSource and do the DataBind to the Dropdownlist passed via reference, I have to add ItemList singoularly (I cannot understand the difference)
public static void loadDDLModelli(ref DropDownList ddl, List<dynamic> objects)
{
Int16 cont = 0;
ddl.Items.Clear();
System.Web.UI.WebControls.ListItem li;
String idModello = "";
String nomeModello = "";
String nomeBrand = "";
String oggetto = "";
List<System.Web.UI.WebControls.ListItem> items = new List<System.Web.UI.WebControls.ListItem>();
foreach (var item in objects)
{
oggetto = item.ToString().Replace("{", "").Replace("}", "");
idModello = oggetto.Split(',')[0].Split('=')[1].Trim();
nomeModello = oggetto.Split(',')[1].Split('=')[1].Trim();
nomeBrand = oggetto.Split(',')[2].Split('=')[1].Trim();
li = new System.Web.UI.WebControls.ListItem(nomeBrand+" - "+nomeModello, idModello);
li.Attributes["Group"] = nomeBrand;
items.Add(li);
cont++;
};
//ddl.DataSource = items;
//ddl.DataBind();
foreach(ListItem i in items)
ddl.Items.Add(i);
ddl.SelectedIndex = -1;
}
I have to make a Report with a list box where multiple results are selected
Image
but when I get to the datatable I do not know how to make it show the result of the different values. Selected.
This is my code...
protected void CargaReporte(object sender, EventArgs e)
{
dsReportes.SP_REPORTE_EVENTOS_CALENDARIODataTable dt = new dsReportes.SP_REPORTE_EVENTOS_CALENDARIODataTable();
dsReportesTableAdapters.SP_REPORTE_EVENTOS_CALENDARIOTableAdapter da = new dsReportesTableAdapters.SP_REPORTE_EVENTOS_CALENDARIOTableAdapter();
ReportDataSource RD = new ReportDataSource();
List<dynamic> lst = new List<dynamic>();
if (ddUsu.SelectedIndex == 0)
{
foreach (ListItem item in ddUsu.Items)
{
if (item.Selected)
{
da.Fill(dt, int.Parse(ddUsu.SelectedValue));
lst.Add(dt);
}
}
}
else
{
da.Fill(dt, int.Parse(ddUsu.SelectedValue == "" ? "0" : ddUsu.SelectedValue));
}
divReporte.Visible = true;
RD.Value = lst.ToArray();
RD.Name = "dbCalendarioEventos";
rvReporteCalendarioEventos.LocalReport.DataSources.Clear();
rvReporteCalendarioEventos.LocalReport.DataSources.Add(RD);
rvReporteCalendarioEventos.LocalReport.ReportEmbeddedResource = "ReporteCalendarioEventos.rdlc";
rvReporteCalendarioEventos.LocalReport.ReportPath = #"Reportes\Calendario\ReporteCalendarioEventos.rdlc";
rvReporteCalendarioEventos.LocalReport.Refresh();
}
How can I fill out the report with two or more results?
Resolved:
Create an additional DataTable to save the information set after the path through the foreach and so I can get the result I share part of the code.
string participante = (txtParticipante.Value == "" ? " " : txtParticipante.Value);
dsReportes.SP_REPORTE_EVENTOS_CALENDARIODataTable dt = new dsReportes.SP_REPORTE_EVENTOS_CALENDARIODataTable();
DataTable table = new DataTable();
dsReportesTableAdapters.SP_REPORTE_EVENTOS_CALENDARIOTableAdapter da = new dsReportesTableAdapters.SP_REPORTE_EVENTOS_CALENDARIOTableAdapter();
ReportDataSource RD = new ReportDataSource();
table = dt.Clone();
var FechaInicio_ini = FechaInicio(CEV_FECHA_INICIO_ini.Value);
var FechaInicio_fin = FechaFin(CEV_FECHA_INICIO_fin.Value);
var FechaFin_ini = FechaInicio(CEV_FECHA_FIN_Ini.Value);
var FechaFin_fin = FechaFin(CEV_FECHA_FIN_fin.Value);
try
{
if (ddUsu.SelectedValue != "")
{
foreach (ListItem item in ddUsu.Items)
{
if (item.Selected == true)
{
da.Fill(dt, int.Parse(item.Value),
FechaInicio_ini, FechaInicio_fin,
FechaFin_ini, FechaFin_fin,(txtParticipante.Value == "" ? " " : txtParticipante.Value));
foreach (DataRow dr in dt)
{
table.Rows.Add(dr.ItemArray);
}
}
}
}
else
{
foreach(ListItem item in ddUsu.Items)
{
da.Fill(dt, int.Parse(item.Value == "" ? "0" : item.Value),
FechaInicio_ini, FechaInicio_fin,
FechaFin_ini, FechaFin_fin, (txtParticipante.Value == "" ? " " : txtParticipante.Value));
foreach (DataRow dr in dt)
{
table.Rows.Add(dr.ItemArray);
}
}
}
divReporte.Visible = true;
RD.Value = table;
RD.Name = "dbCalendarioEventos";
rvReporteCalendarioEventos.LocalReport.DataSources.Clear();
rvReporteCalendarioEventos.LocalReport.DataSources.Add(RD);
rvReporteCalendarioEventos.LocalReport.ReportEmbeddedResource = "ReporteCalendarioEventos.rdlc";
rvReporteCalendarioEventos.LocalReport.ReportPath = #"Reportes\Calendario\ReporteCalendarioEventos.rdlc";
rvReporteCalendarioEventos.LocalReport.Refresh();
}
catch(Exception ex) { }
}
image 2
I'm currently working on my shopping cart. and I'm wondering how I can add drop down list column for quantity in every item that is inside the Cart. And also I want the limit of drop down list to be the number of the product stock. Hoping for a brief explanation. Thank you. :)
Cart.aspx.cs
protected void theCart()
{
var dt = new DataTable();
double totalPrice = 0;
dt.Columns.Add("product_name");
dt.Columns.Add("product_price");
dt.Columns.Add("product_stock");
List<ShoppingCartModel> shoppingList = (List<ShoppingCartModel>)Session["memberCart"];
if (shoppingList != null)
{
foreach (var item in shoppingList)
{
dt.Rows.Add(item.ProductName, item.Price, item.ProductStock);
totalPrice += item.Price;
}
}
lbl_total.Text = totalPrice.ToString();
MyGridView.DataSource = dt;
MyGridView.DataBind();
}
WebShop.aspx.cs
protected void pro_tbl_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName == "addtocart")
{
List<ShoppingCartModel> shoppingList = (List<ShoppingCartModel>)Session["memberCart"];
if (shoppingList == null)
{
shoppingList = new List<ShoppingCartModel>();
}
ShoppingCartModel shoppingModel = new ShoppingCartModel();
shoppingModel.ProductId = ((HiddenField)e.Item.FindControl("lblProductId")).Value;
shoppingModel.ProductName = ((Label)e.Item.FindControl("lbl_pname")).Text;
shoppingModel.ProductDescription = ((Label)e.Item.FindControl("lbl_pdesc")).Text;
shoppingModel.ProductStock = Convert.ToInt32(((Label)e.Item.FindControl("lbl_pstock")).Text);
shoppingModel.Price = Convert.ToDouble(((Label)e.Item.FindControl("lbl_price")).Text);
shoppingList.Add(shoppingModel);
Session["memberCart"] = shoppingList;
lbl_result.Text = "Product has been added to the cart";
}
}
I have two dropdownlist controls on an add/edit form page, one for countries (called CountryCode) and one for regions/states (called ProvinceCode). The code has been set up so that, when users select "United States" from the country dropdownlist, then the region dropdownlist is populated with all valid US states. If the user selects "Canada" from the country dropdownlist, then the region dropdownlist is populated with valid provinces. This functionality works fine, but when "Canada" is selected, for some reason, the region dropdownlist's value is never saved to the database. I am not sure why this is, especially since I can save US states just fine.
This is the code that is meant to populate the country and region dropdownlists:
protected void Page_Init(object sender, EventArgs e)
{
CountryCode.DataSource = CountryDataSource.LoadAll("Name");
CountryCode.DataBind();
InitCountryAndProvince();
}
private void InitCountryAndProvince()
{
//MAKE SURE THE CORRECT ADDRESS IS SELECTED
Address address = this.Address;
bool foundCountry = false;
if (!string.IsNullOrEmpty(address.CountryCode))
{
ListItem selectedCountry = CountryCode.Items.FindByValue(address.CountryCode);
if (selectedCountry != null)
{
CountryCode.SelectedIndex = CountryCode.Items.IndexOf(selectedCountry);
foundCountry = true;
}
}
if (!foundCountry)
{
Warehouse defaultWarehouse = AbleContext.Current.Store.DefaultWarehouse;
ListItem selectedCountry = CountryCode.Items.FindByValue(defaultWarehouse.CountryCode);
if (selectedCountry != null) CountryCode.SelectedIndex = CountryCode.Items.IndexOf(selectedCountry);
}
//MAKE SURE THE PROVINCE LIST IS CORRECT FOR THE COUNTRY
UpdateCountry();
//NOW LOOK FOR THE PROVINCE TO SET
ListItem selectedProvince = ProvinceCode.Items.FindByValue(address.Province);
if (selectedProvince != null) ProvinceCode.SelectedIndex = ProvinceCode.Items.IndexOf(selectedProvince);
}
private void UpdateCountry()
{
//SEE WHETHER POSTAL CODE IS REQUIRED
string[] countries = AbleContext.Current.Store.Settings.PostalCodeCountries.Split(",".ToCharArray());
//PostalCodeRequired.Enabled = (Array.IndexOf(countries, Country.SelectedValue) > -1);
//SEE WHETHER PROVINCE LIST IS DEFINED
IList<Province> provinces = ProvinceDataSource.LoadForCountry(CountryCode.SelectedValue);
if (provinces.Count > 0)
{
IEnumerable<Province> sortedProvinces = provinces.OrderBy(f => f.Name);
provinces = sortedProvinces.ToList();
ProvinceCode.Visible = false;
ProvinceCode.Visible = true;
ProvinceCode.Items.Clear();
ProvinceCode.Items.Add(string.Empty);
foreach (Province province in provinces)
{
string provinceValue = (!string.IsNullOrEmpty(province.ProvinceCode) ? province.ProvinceCode : province.Name);
ProvinceCode.Items.Add(new ListItem(province.Name, provinceValue));
}
ListItem selectedProvince = FindSelectedProvince();
if (selectedProvince != null) selectedProvince.Selected = true;
ProvinceCode.Enabled = true;
ProvinceCode.Text = string.Empty;
}
else
{
ProvinceCode.Visible = true;
ProvinceCode.Visible = false;
ProvinceCode.Items.Clear();
//Province2Required.Enabled = false;
}
}
private ListItem FindSelectedProvince()
{
string defaultValue = ProvinceCode.Text;
if (string.IsNullOrEmpty(defaultValue)) defaultValue = Request.Form[ProvinceCode.UniqueID];
if (string.IsNullOrEmpty(defaultValue)) return null;
defaultValue = defaultValue.ToUpperInvariant();
foreach (ListItem item in ProvinceCode.Items)
{
string itemText = item.Text.ToUpperInvariant();
string itemValue = item.Value.ToUpperInvariant();
if (itemText == defaultValue || itemValue == defaultValue) return item;
}
return null;
}
protected void Country_Changed(object sender, EventArgs e)
{
//UPDATE THE FORM FOR THE NEW COUNTRY
UpdateCountry();
}
This is the section of the save method that contains the country and region dropdownlist controls:
private void SaveCustomerInfo(int CustID)
{
int currentUserID = AbleContext.Current.UserId;
string editQuery = "UPDATE Customers SET BillToRegion = #BillToRegion, BillToCountry = #BillToCountry WHERE CustomerID = #CustomerID";
string addQuery = "INSERT INTO Customers (BillToRegion, BillToCountry) VALUES(#BillToRegion, #BillToCountry)";
try
{
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["AbleCommerce"].ToString()))
{
cn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.Parameters.Add(new SqlParameter("#BillToRegion", ProvinceCode.SelectedValue));
cmd.Parameters.Add(new SqlParameter("#BillToCountry", CountryCode.SelectedValue));
cmd.ExecuteNonQuery();
cn.Close();
}
}
catch (Exception exception)
{
Logger.Warn("Admin\\People\\Customers\\EditCustomer.aspx - SaveCustomerInfo", exception);
}
And this is the code that is called when the page loads to populate fields with values from the database (if the user is editing an existing entry):
protected void Page_Load(object sender, EventArgs e)
{
_CustomerID = AlwaysConvert.ToInt(Request.QueryString["CustomerID"]);
int.TryParse(Request.QueryString["CustomerID"], out _CustomerID);
if (_CustomerID == 0)
{
AddBtn.Visible = true;
EditBtn.Visible = false;
}
else
{
custIDHidden.Value = _CustomerID.ToString();
AddBtn.Visible = false;
EditBtn.Visible = true;
}
if (!Page.IsPostBack)
{
if (_CustomerID != 0)
{
string selectQuery = "BillToRegion, BillToCountry FROM Customers WHERE CustomerID = #CustomerID";
try
{
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["AbleCommerce"].ToString()))
{
cn.Open();
SqlCommand cmd = new SqlCommand(selectQuery, cn);
cmd.Parameters.Add(new SqlParameter("#CustomerID", custIDHidden.Value));
using (IDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
ProvinceCode.SelectedValue = reader["BillToRegion"].ToString();
CountryCode.SelectedValue = reader["BillToCountry"].ToString();
}
}
cn.Close();
}
}
catch (Exception x)
{
Logger.Warn("Admin\\People\\Customers\\EditCustomer.aspx - Page_Load", x);
}
}
}
}
I am creating a CheckBoxList in a class file and am using an HTMLTextWriter to render the control.
I'm using the following code to store the selected values in a string:
string YrStr = "";
for (int i = 0; i < YrChkBox.Items.Count; i++)
{
if (YrChkBox.Items[i].Selected)
{
YrStr += YrChkBox.Items[i].Value + ";";
}
}
I stepped through the code and it doesn't seem to hit the inside of the if statement & the selected value attribute is false every time ... Anyone have an idea of how I can address this?
I populate it using the following:
YrChkBox.Items.Add(new ListItem("Item 1", "Item1"));
In your ASPX page you've got the list like this:
<asp:CheckBoxList ID="YrChkBox" runat="server"
onselectedindexchanged="YrChkBox_SelectedIndexChanged"></asp:CheckBoxList>
<asp:Button ID="button" runat="server" Text="Submit" />
In your code behind aspx.cs page, you have this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Populate the CheckBoxList items only when it's not a postback.
YrChkBox.Items.Add(new ListItem("Item 1", "Item1"));
YrChkBox.Items.Add(new ListItem("Item 2", "Item2"));
}
}
protected void YrChkBox_SelectedIndexChanged(object sender, EventArgs e)
{
// Create the list to store.
List<String> YrStrList = new List<string>();
// Loop through each item.
foreach (ListItem item in YrChkBox.Items)
{
if (item.Selected)
{
// If the item is selected, add the value to the list.
YrStrList.Add(item.Value);
}
else
{
// Item is not selected, do something else.
}
}
// Join the string together using the ; delimiter.
String YrStr = String.Join(";", YrStrList.ToArray());
// Write to the page the value.
Response.Write(String.Concat("Selected Items: ", YrStr));
}
Ensure you use the if (!IsPostBack) { } condition because if you load it every page refresh, it's actually destroying the data.
Try something like this:
foreach (ListItem listItem in YrChkBox.Items)
{
if (listItem.Selected)
{
//do some work
}
else
{
//do something else
}
}
check boxlist selected values with seperator
string items = string.Empty;
foreach (ListItem i in CheckBoxList1.Items)
{
if (i.Selected == true)
{
items += i.Text + ",";
}
}
Response.Write("selected items"+ items);
An elegant way to implement this would be to make an extension method, like this:
public static class Extensions
{
public static List<string> GetSelectedItems(this CheckBoxList cbl)
{
var result = new List<string>();
foreach (ListItem item in cbl.Items)
if (item.Selected)
result.Add(item.Value);
return result;
}
}
I can then use something like this to compose a string will all values separated by ';':
string.Join(";", cbl.GetSelectedItems());
// Page.aspx //
// To count checklist item
int a = ChkMonth.Items.Count;
int count = 0;
for (var i = 0; i < a; i++)
{
if (ChkMonth.Items[i].Selected == true)
{
count++;
}
}
// Page.aspx.cs //
// To access checkbox list item's value //
string YrStrList = "";
foreach (ListItem listItem in ChkMonth.Items)
{
if (listItem.Selected)
{
YrStrList = YrStrList + "'" + listItem.Value + "'" + ",";
}
}
sMonthStr = YrStrList.ToString();
// aspx.cs
// Load CheckBoxList selected items into ListBox
int status = 1;
foreach (ListItem s in chklstStates.Items )
{
if (s.Selected == true)
{
if (ListBox1.Items.Count == 0)
{
ListBox1.Items.Add(s.Text);
}
else
{
foreach (ListItem list in ListBox1.Items)
{
if (list.Text == s.Text)
{
status = status * 0;
}
else
{
status = status * 1;
}
}
if (status == 0)
{ }
else
{
ListBox1.Items.Add(s.Text);
}
status = 1;
}
}
}
}