Design Time Error in Composite COntrol in ASP.NET - c#

I have created a composite control. There is no build error in it.
In the composite control i am using a Entity Framework Object
The problem is that in the design window i get the error message as shown in PIC:
There is no Error during build and composite control works well.
I just want to remove this error from Design Time window
EDIT:
Its like how i am adding the composite control:
<tr>
<td colspan="3">
<cc1:AdditionalColumnsCustomControl ID="AdditionalColumnsCustomControl1" runat="server"
MainCssClass="A" ControlMode="New" TableID="1" AreValidatorsStatic="true"
CustomControlWrapper="TableWrapper" ValidationGroup="vl" />
</td>
</tr>
In this case how i can i code to get rid of this Design surface error.
Composite COntrol SOurce COde:
public class AddRowCustomControl : CompositeControl
{
public void Clear()
{
Control c = (Control)FindControl(controlID);
if (c.GetType() == typeof(DropDownList))
{
DropDownList dl = c as DropDownList;
ListItem lsa = dl.SelectedItem;
lsa.Selected = false;
}
else if (c.GetType() == typeof(ListBox))
{
ListBox lb = c as ListBox;
foreach (ListItem ls in lb.Items)
{
if (ls.Selected)
{
ls.Selected = false;
}
}
}
else if (c.GetType() == typeof(RadioButtonList))
{
RadioButtonList rl = c as RadioButtonList;
foreach (ListItem ls in rl.Items)
{
if (ls.Selected)
{
ls.Selected = false;
}
}
}
else if (c.GetType() == typeof(CheckBoxList))
{
CheckBoxList cl = c as CheckBoxList;
foreach (ListItem ls in cl.Items)
{
if (ls.Selected)
{
ls.Selected = false;
}
}
}
else if (c.GetType() == typeof(CheckBox))
{
CheckBox chk = c as CheckBox;
chk.Checked = false;
}
else
{
TextBox tx = c as TextBox;
tx.Text = "";
}
}
public void Rebind()
{
Control c = (Control)FindControl(controlID);
fillControl(ref c , RowID , ColumnID);
}
public string SaveControlValuesInDB()
{
using (ExtEntities context = new ExtEntities())
{
if (RowID != null && ColumnID != null)
{
EntityData ed = context.EntityDatas.Where(p => p.ColID == ColumnID && p.RowID == RowID).FirstOrDefault();
if (ed == null)
{
ed = new EntityData();
ed.RowID = Convert.ToInt32(RowID);
ed.ColID = ColumnID;
ed.ColValue = ControlValue;
context.AddToEntityDatas(ed);
context.SaveChanges();
return "Successfully Added";
}
else
{
ed.ColValue = ControlValue;
context.SaveChanges();
return "Successfully Updated";
}
}
else
{
return "Exception Invalid Row ID";
}
}
}
public int? RowID
{
get;
set;
}
public enum Modes
{
New = 0,
Modify = 1,
ModifyInGrid = 2,
}
public Modes? ControlMode
{
get;
set;
}
public int ColumnID
{
get;
set;
}
public string ValidationGroup
{
get;
set;
}
/// <summary>
/// Specifes the Display mode of the Validators "Static or Dynamic"
/// </summary>
public bool? AreValidatorsStatic
{
get;
set;
}
/// <summary>
/// If true, the wrapper will be DIV's else Table
/// </summary>
public Wrapper CustomControlWrapper
{
get;
set;
}
public enum Wrapper
{
DivWrapper = 0,
TableWrapper = 1,
}
/// <summary>
/// Css Class Name for Custom Control
/// </summary>
public string MainCssClass
{
get;
set;
}
/// <summary>
/// Css Class Name for Custom Control Label
/// </summary>
public string LabelCssClass
{
get;
set;
}
/// <summary>
/// Css Class Name for Custom Control's Main Control
/// </summary>
public string ControlCssClass
{
get;
set;
}
/// <summary>
/// Css Class Name for Custom Control's Validators
/// </summary>
public string ValidatorCssClass
{
get;
set;
}
protected override void OnLoad(EventArgs e)
{
if (AreValidatorsStatic == null)
{
AreValidatorsStatic = false;
}
if (CustomControlWrapper == null)
{
CustomControlWrapper = Wrapper.DivWrapper;
}
if (string.IsNullOrEmpty(MainCssClass))
{
MainCssClass = "CustomControlMainClass";
}
if (string.IsNullOrEmpty(ControlCssClass))
{
ControlCssClass = "ControlCssClass";
}
if (string.IsNullOrEmpty(LabelCssClass))
{
LabelCssClass = "LabelCssClass";
}
if (string.IsNullOrEmpty(ValidatorCssClass))
{
ValidatorCssClass = "ValidatorCssClass";
}
if (ControlMode == null)
{
ControlMode = Modes.New;
}
base.OnLoad(e);
}
string controlID = "ControlID";
public string ControlValue
{
get
{
Control c = (Control)FindControl(controlID);
StringBuilder sb = new StringBuilder();
if (c.GetType() == typeof(DropDownList))
{
DropDownList dl = c as DropDownList;
sb.Append(dl.Text);
return sb.ToString();
}
else if (c.GetType() == typeof(ListBox))
{
ListBox lb = c as ListBox;
foreach (ListItem item in lb.Items)
{
if (item.Selected)
{
sb.Append(item.Text + "`");
}
}
return sb.ToString().TrimEnd('`');
}
else if (c.GetType() == typeof(RadioButtonList))
{
RadioButtonList rl = c as RadioButtonList;
sb.Append(rl.SelectedItem.Value);
return sb.ToString();
}
else if (c.GetType() == typeof(CheckBoxList))
{
CheckBoxList cl = c as CheckBoxList;
foreach (ListItem li in cl.Items)
{
if (li.Selected == true)
{
sb.Append(li.Text + "`");
}
}
return sb.ToString().TrimEnd('`');
}
else if (c.GetType() == typeof(CheckBox))
{
CheckBox chk = c as CheckBox;
return chk.Checked ? "TRUE" : "";
}
else
{
TextBox tx = c as TextBox;
return tx.Text;
}
}
}
private void AddOptions(string[] options, ref Control c)
{
if (c.GetType() == typeof(DropDownList))
{
DropDownList dl = c as DropDownList;
foreach (string item in options)
{
dl.Items.Add(item);
}
c = dl;
}
else if (c.GetType() == typeof(ListBox))
{
ListBox lb = c as ListBox;
foreach (string item in options)
{
lb.Items.Add(item);
}
c = lb;
}
else if (c.GetType() == typeof(RadioButtonList))
{
RadioButtonList rl = c as RadioButtonList;
foreach (string item in options)
{
rl.Items.Add(item);
}
c = rl;
}
else if (c.GetType() == typeof(CheckBoxList))
{
CheckBoxList cl = c as CheckBoxList;
foreach (string item in options)
{
cl.Items.Add(item);
}
c = cl;
}
}
protected override void CreateChildControls()
{
string ts = MainCssClass;
using (ExtEntities context = new ExtEntities())
{
EntityAttribute _Attribute = context.EntityAttributes.Where(p => p.ID == ColumnID).FirstOrDefault();
if (_Attribute != null)
{
Panel pnl = new Panel();
string[] _options = null;
if (_Attribute.ControlOptions != null)
{
_options = _Attribute.ControlOptions.Split('`');
}
Label lt = new Label();
lt.ID = "LabelID";
lt.Text = _Attribute.ColumnLabel;
Control c = null;
int? MaxLength = _Attribute.MaxLength;
bool Invalidate_Validator = false;
switch (_Attribute.AttributeTypeID)
{
case 1:
TextBox sl = new TextBox();
if (_Attribute.MaxLength != null)
sl.MaxLength = Convert.ToInt32(_Attribute.MaxLength);
c = sl;
break;
case 2:
TextBox ml = new TextBox();
ml.TextMode = TextBoxMode.MultiLine;
if (_Attribute.MaxLength != null)
ml.MaxLength = Convert.ToInt32(_Attribute.MaxLength);
c = ml;
break;
case 3:
DropDownList dl = new DropDownList();
c = dl;
break;
case 4:
ListBox lb = new ListBox();
lb.SelectionMode = ListSelectionMode.Multiple;
c = lb;
break;
case 5:
TextBox p = new TextBox();
p.TextMode = TextBoxMode.Password;
if (_Attribute.MaxLength != null)
p.MaxLength = Convert.ToInt32(_Attribute.MaxLength);
c = p;
break;
case 6:
CheckBox ck = new CheckBox();
Invalidate_Validator = true;
ck.Text = _options != null ? _options[0] : "N/A";
c = ck;
break;
//case 7:
// RadioButton rb = new RadioButton();
// rb.Text = _options != null ? _options[0] : "N/A";
// c = rb;
// break;
case 8:
RadioButtonList rb_list = new RadioButtonList();
c = rb_list;
break;
case 9:
CheckBoxList ck_list = new CheckBoxList();
Invalidate_Validator = true;
c = ck_list;
break;
default:
break;
}
RequiredFieldValidator req = null;
RegularExpressionValidator regx = null;
AddOptions(_options, ref c);
c.ID = controlID;
if (!Invalidate_Validator)
{
if (_Attribute.Mandatory)
{
req = new RequiredFieldValidator();
req.ControlToValidate = c.ID;
req.ErrorMessage = _Attribute.ValidationMessage;
req.Text = "*";
req.Display = AreValidatorsStatic == true ? ValidatorDisplay.Static : ValidatorDisplay.Dynamic;
req.ValidationGroup = ValidationGroup;
}
if (_Attribute.RegularExpressionValue != null)
{
regx = new RegularExpressionValidator();
regx.ControlToValidate = c.ID;
regx.ErrorMessage = _Attribute.ValidationMessage;
regx.Text = "*";
regx.ValidationGroup = ValidationGroup;
regx.ValidationExpression = _Attribute.RegularExpressionValue;
regx.Display = AreValidatorsStatic == true ? ValidatorDisplay.Static : ValidatorDisplay.Dynamic;
}
}
if (ControlMode == Modes.Modify)
{
fillControl(ref c, RowID, ColumnID);
}
if (CustomControlWrapper == Wrapper.DivWrapper)
{
pnl.Controls.Add(new LiteralControl(#"<div class=""" + MainCssClass + #"""><div class=""" + LabelCssClass + #""">"));
if (ControlMode != Modes.ModifyInGrid)
pnl.Controls.Add(lt);
pnl.Controls.Add(new LiteralControl(#"</div><div class=""" + ControlCssClass + #""">"));
pnl.Controls.Add(c);
pnl.Controls.Add(new LiteralControl(#"</div><div class=""" + ValidatorCssClass + #""">"));
if (req != null)
pnl.Controls.Add(req);
if (regx != null)
pnl.Controls.Add(regx);
pnl.Controls.Add(new LiteralControl(#"</div>"));
pnl.Controls.Add(new LiteralControl(#"</div>"));
}
else
{
pnl.Controls.Add(new LiteralControl(#"<table class=""" + MainCssClass + #"""><tr><td class=""" + LabelCssClass + #""">"));
if (ControlMode != Modes.ModifyInGrid)
pnl.Controls.Add(lt);
pnl.Controls.Add(new LiteralControl(#"</td><td class=""" + ControlCssClass + #""">"));
pnl.Controls.Add(c);
pnl.Controls.Add(new LiteralControl(#"</td><td class=""" + ValidatorCssClass + #""">"));
if (req != null)
pnl.Controls.Add(req);
if (regx != null)
pnl.Controls.Add(regx);
pnl.Controls.Add(new LiteralControl(#"</td></tr>"));
pnl.Controls.Add(new LiteralControl(#"</table>"));
}
Controls.Add(pnl);
}
}
}
private void fillControl(ref Control c, int? RowID, int ColumnID)
{
using (ExtEntities context = new ExtEntities())
{
EntityData obj = context.EntityDatas.Where(p => p.RowID == RowID && p.ColID == ColumnID).FirstOrDefault();
if (obj != null)
{
string[] values = obj.ColValue.Split('`');
string value = obj.ColValue;
if (c.GetType() == typeof(DropDownList))
{
DropDownList dl = c as DropDownList;
dl.Items.FindByText(value).Selected = true;
}
else if (c.GetType() == typeof(ListBox))
{
ListBox lb = c as ListBox;
foreach (var item in values)
{
lb.Items.FindByText(value).Selected = true;
}
}
else if (c.GetType() == typeof(RadioButtonList))
{
RadioButtonList rl = c as RadioButtonList;
foreach (var item in values)
{
rl.Items.FindByText(item).Selected = true;
}
}
else if (c.GetType() == typeof(CheckBoxList))
{
CheckBoxList cl = c as CheckBoxList;
foreach (var item in values)
{
cl.Items.FindByText(value).Selected = true;
}
}
else if (c.GetType() == typeof(CheckBox))
{
CheckBox chk = c as CheckBox;
chk.Checked = value == "TRUE" ? true : false;
}
else
{
TextBox tx = c as TextBox;
tx.Text = value;
}
}
}
}
Thanks
Any help is appreciated.

This is due to the fact that at design time the EF objects won't be available/instantiated. Can verify whether your control is currently be displayed on a design surface with the DesignMode property (MSDN doc):
if(this.DesignMode == false)
{
//do normal instantiations of objects etc.
}
else
{
//do work related to creating a design time view of your control
}

It sounds like you have a dependency that the designer is unable to resolve. You can use the DesignMode flag to help with this:
http://msdn.microsoft.com/en-us/library/system.componentmodel.component.designmode.aspx

Related

How to add a Group of data with only one unique group ID using C# in MSSQL?

I want to create a group of registered clients using different products, categories and sub categories.
I am using asp.net C# and updating database using entity model.
int PID = Convert.ToInt32(ddProduct.SelectedValue);
if (isValidName(txtGroupName.Text))
{
if (ddBusinessCategory.SelectedValue == "0")
{
var clients = db.Client_Master.Where(c => c.InquiredFor == PID).ToList();
foreach (var clt in clients)
{
Group_Master gobj = new Group_Master();
gobj.GName = txtGroupName.Text;
gobj.ProductID = PID;
gobj.CatID = null;
gobj.SubCatID = null;
gobj.ClientID = clt.CID;
gobj.CreatedBy = Convert.ToInt32(((User_Master)Session["User"]).UID);
gobj.CreatedOn = DateTime.Now;
db.Group_Master.AddObject(gobj);
db.SaveChanges();
}
}
else
{
if (ddSubCategory.SelectedValue == "0")
{
int CID = Convert.ToInt32(ddBusinessCategory.SelectedValue);
var clients = db.Client_Master.Where(c => c.InquiredFor == PID && c.BusinessCategory == CID).ToList();
foreach (var clt in clients)
{
Group_Master gobj = new Group_Master();
gobj.GName = txtGroupName.Text;
gobj.ProductID = PID;
gobj.CatID = CID;
gobj.SubCatID = null;
gobj.ClientID = clt.CID;
gobj.CreatedBy = Convert.ToInt32(((User_Master)Session["User"]).UID);
gobj.CreatedOn = DateTime.Now;
db.Group_Master.AddObject(gobj);
db.SaveChanges();
}
}
else
{
int CID = Convert.ToInt32(ddBusinessCategory.SelectedValue);
int SID = Convert.ToInt32(ddSubCategory.SelectedValue);
var clients = db.Client_Master.Where(c => c.InquiredFor == PID && c.BusinessCategory == CID && c.SubCategory == SID).ToList();
foreach (var clt in clients)
{
Group_Master gobj = new Group_Master();
gobj.GName = txtGroupName.Text;
gobj.ProductID = PID;
gobj.CatID = CID;
gobj.SubCatID = SID;
gobj.ClientID = clt.CID;
gobj.CreatedBy = Convert.ToInt32(((User_Master)Session["User"]).UID);
gobj.CreatedOn = DateTime.Now;
db.Group_Master.AddObject(gobj);
db.SaveChanges();
}
}
}
Groups();
}
I tried to add Group ID using many ways but didn't succeed.
Please suggest me how can I solve this.
Thank you !!
You should create new table ClientsProducts, which will have reference to Client ID and Product ID. This is called One-to-Many Relationships.
You can read here about this here.
I Solved this by taking the ID of last data of list and save as a group ID so, with the help of this we get unique group ID.
if (ddBusinessCategory.SelectedValue == "0")
{
var clients = db.Client_Master.Where(c => c.InquiredFor == PID).ToList();
int GrpID = 0;
if (clients.Count() > 0)
{
foreach (var clt in clients)
{
if (ProductGrp(PID, clt.CID))
{
Group_Master gobj = new Group_Master();
gobj.GrpID = 0;
gobj.GName = txtGroupName.Text;
gobj.ProductID = PID;
gobj.CatID = null;
gobj.SubCatID = null;
gobj.ClientID = clt.CID;
gobj.CreatedBy = Convert.ToInt32(((User_Master)Session["User"]).UID);
gobj.CreatedOn = DateTime.Now;
db.Group_Master.AddObject(gobj);
db.SaveChanges();
GrpID = gobj.GID;
}
else
{
ScriptManager.RegisterStartupScript(Page, this.GetType(), "myscript()", "bootbox.alert({title: '<b>Error</b>',message: '<b>Group already exist.</b>',});", true);
break;
}
}
List<Group_Master> ggobj = db.Group_Master.Where(g => g.ProductID == PID && g.CatID == null && g.SubCatID == null).ToList();
foreach (var gid in ggobj)
{
if (gid.GrpID == 0)
{
Group_Master gmobj = db.Group_Master.Single(s => s.GID == gid.GID);
gmobj.GrpID = GrpID;
db.SaveChanges();
}
}
}
else
{
ScriptManager.RegisterStartupScript(Page, this.GetType(), "myscript()", "bootbox.alert({title: '<b>Error</b>',message: '<b>No Clients exist.</b>',});", true);
}
}

Dropdownlist with optgroup using WebControlAdapters

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;
}

Text box Auto Generate code not working

I am developing the my asp.net project, I'm try to make ASP.net text box for Auto Generate code, but its not working correctly, sample Auto Generate code = ID1.
I'm try to use this part,
string txt = txtBatchNo.Text;
txtBatchNo.Text = "C" + Convert.ToInt32(txt.Substring(1, txt.Length - 1)) + 1;
Code:
protected void btnAdd_Click(object sender, EventArgs e)
{
int newId = 1;
if (selectGRNDetailId == -1)
{
{
try
{
if (dtFabricItem.Rows.Count > 0)
{
newId = Convert.ToInt32(dtFabricItem.Rows[dtFabricItem.Rows.Count - 1]["GRNDetailsID"].ToString()) + 1;
}
}
catch (Exception)
{
newId = 1;
}
}
}
else
{
newId = selectGRNDetailId;
}
if (dtFabricItem == null)
{
CreateFabricDetails();
dtFabricItem = dt;
}
else
{
CreateFabricDetails();
}
DataRow dr2 = null;
dr2 = dt.NewRow();
dr2["GRNDetailsID"] = newId;
dr2["GRNDetailID"] = selectGRNId;
dr2["BatchNO"] = txtBatchNo.Text;
dr2["ItemId"] = Convert.ToInt32(ddlYarnName.SelectedValue);
dr2["ItemName"] = ddlYarnName.SelectedItem.Text;
dr2["LotId"] = Convert.ToInt32(ddlLotNo.SelectedValue);
dr2["LotName"] = ddlLotNo.SelectedItem.Text;
dr2["FibetLot"] = txtFiberLot.Text;
dr2["ContainsNo"] = txtContainsNO.Text;
dr2["Shade"] = txtShade.Text;
dr2["Quantity"] = Convert.ToDecimal(txtQty.Text).ToString();
dr2["YarnPrice"] = Convert.ToDecimal(txtYarnPrice.Text).ToString();
dr2["Cornweight"] = Convert.ToDecimal(txtCornWeight.Text).ToString();
dr2["BoxWeight"] = Convert.ToDecimal(txtBoxWeight.Text).ToString();
dr2["NumberofCones"] = Convert.ToDecimal(txtNumberofcones.Text).ToString();
dr2["Numberofboxes"] = Convert.ToDecimal(txtNumberofboxes.Text).ToString();
dt.Rows.Add(dr2);
//txtNumberofcones.Text = (Convert.ToDecimal(txtBoxWeight.Text) / Convert.ToDecimal(txtCornWeight.Text)).ToString();
if (dtFabricItem == null || dtFabricItem.Rows.Count == 0)
{
dtFabricItem = dt;
dtFabricItem.PrimaryKey = new DataColumn[] { dtFabricItem.Columns["GRNDetailsID"] };
}
else
{
dtFabricItem.PrimaryKey = new DataColumn[] { dtFabricItem.Columns["GRNDetailsID"] };
dtFabricItem.Merge(dt);
}
//dtFabricItem.PrimaryKey = new DataColumn[] { dtFabricItem.Columns["GRNDetailsID"] };
dtFabricItem.AcceptChanges();
gvrItemDetails.DataSource = dtFabricItem;
gvrItemDetails.DataBind();
selectGRNDetailId = -1;
ClearDetails();
}
TextBox Id = `txtBatchNo`

asp.net page is loading very slow

Well i'm working an application which use a connection with SharePoint to load the list items.
I'm also using a dynamic table so new rows can be added by the user.
It takes more than 7 seconds before my page is asp.net page. I checked this with firebug.
Below is the code of my page:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Client;
namespace AdminCareWeb
{
public partial class DocumentToevoegen : System.Web.UI.Page
{
#region globalevars
SharePointContextToken contextToken;
string accessToken;
Uri sharepointUrl;
string contextTokenString;
string logoHoofding;
int initNumRows = 15;
public string jsSharePointURL;
//Instanties aanmaken van de klasses
static List<TableRow> TableRows = new List<TableRow>();
static Dictionary<int, Artikels> dicArtikels = new Dictionary<int, Artikels>();
Document huidigDocument = new Document();
Klanten huidigeKlant = new Klanten();
#endregion
#region properties
private int numOfRows
{
get
{
if (ViewState["RowsCount"] == null)
{
return 0;
}
else
{
return (int)ViewState["RowsCount"];
}
}
set
{
ViewState["RowsCount"] = value;
}
}
#endregion
protected void Page_Load(object sender, EventArgs e)
{
try
{
string vorigePagina = Request.UrlReferrer.ToString();
//Controleer of de pagina gerefreshd werd of voor het eerst geladen wordt.
if (!vorigePagina.Contains("DocumentToevoegen.aspx"))
{
TableRows.Clear();
//Als de pagina voor de eerste keer geladen wordt moet de tabel leeggemaakt worden.
dicArtikels.Clear();
}
//Generate the Rows on Initial Load
if (!Page.IsPostBack && dicArtikels.Count == 0)
{
numOfRows = initNumRows;
Artikels artikel = new Artikels();
for (int i = 0; i < numOfRows; i++)
{
dicArtikels.Add(i, artikel);
}
}
GenerateTable(0, numOfRows);
//Controleer of security tokens al aanwezig zijn. Indien deze niet aanwezig zijn maak ze globaal aan.
if (PassThrough.contextTokenString != null)
{
ClientContext clientContext = ContextTokensOphalen();
jsSharePointURL = PassThrough.sharepointUrl.ToString();
}
else if (!IsPostBack)
{
Response.Write("Could not find a context token.");
return;
}
}
catch (Exception ex)
{
huidigDocument.log("DocumentToevoegen.aspx", "Page_Load", ex.Message.ToString());
}
}
protected void Page_LoadComplete(object sender, EventArgs e)
{
ClientContext clientContext = ContextTokensOphalen();
try
{
bool foutief = false; ;
string adresgegevens = "";
#region parameters ophalen
Parameters ledig = new Parameters();
ledig.ledigParameters();
huidigDocument.ParametersLookup(clientContext);
huidigDocument.Parameters1Tekstregel(clientContext);
huidigDocument.ParametersMeerdereTekstregels(clientContext);
huidigDocument.ParametersJaNeen(clientContext);
//Controleer of de bankgegevens ingevuld werden.
if (Parameters.Bankgegevens != null && !string.IsNullOrEmpty(Parameters.Bankgegevens))
{
foutief = false;
lblBankgegevens.Text = Parameters.Bankgegevens.Replace("\r\n", "<br />");
}
if (Parameters.Naam != null && !string.IsNullOrEmpty(Parameters.Naam))
{
foutief = false;
adresgegevens += Parameters.Naam + "<br>";
}
if (Parameters.Adres != null && !string.IsNullOrEmpty(Parameters.Adres))
{
foutief = false;
adresgegevens += Parameters.Adres + "<br>";
}
if (Parameters.Adres2 != null && !string.IsNullOrEmpty(Parameters.Adres2))
{
foutief = false;
adresgegevens += Parameters.Adres2 + "<br>";
}
if (Parameters.Postcode != null && !string.IsNullOrEmpty(Parameters.Postcode))
{
foutief = false;
adresgegevens += Parameters.Postcode;
}
if (Parameters.Plaats != null && !string.IsNullOrEmpty(Parameters.Plaats))
{
foutief = false;
adresgegevens += " " + Parameters.Plaats + "<br>";
}
if (Parameters.Telefoon != null && Parameters.Telefoon.Length > 3)
{
foutief = false;
adresgegevens += "Tel: " + Parameters.Telefoon + "<br>";
}
if (Parameters.GSM != null && Parameters.GSM.Length > 3)
{
foutief = false;
adresgegevens += "GSM: " + Parameters.GSM + "<br>";
}
if (Parameters.Fax != null && Parameters.Fax.Length > 3)
{
foutief = false;
adresgegevens += "Fax: " + Parameters.Fax + "<br>";
}
if (Parameters.Ondernemingsnummer != null && Parameters.Ondernemingsnummer.Length > 3)
{
foutief = false;
adresgegevens += "BTW " + Parameters.Ondernemingsnummer + "<br>";
}
if (Parameters.RPR != null && !string.IsNullOrEmpty(Parameters.RPR))
{
foutief = false;
adresgegevens += "RPR " + Parameters.RPR + "<br>";
}
if (Parameters.Website != null && !string.IsNullOrEmpty(Parameters.Website))
{
foutief = false;
adresgegevens += Parameters.Website + "<br>";
}
if (Parameters.Email != null && !string.IsNullOrEmpty(Parameters.Email))
{
foutief = false;
adresgegevens += Parameters.Email + "<br>";
}
if (Parameters.Logo != null && Parameters.LogoHoofding.ToString() == "")
{
foutief = false;
imgLogo.ImageUrl = Parameters.Logo;
imgLogo.Visible = true;
}
if (Parameters.LogoHoofding.ToString() != "")
{
logoHoofd.Style.Add("BACKGROUND-IMAGE", "url(" + Parameters.LogoHoofding + ");width:794px;");
foutief = false;
logoHoofding = Parameters.LogoHoofding;
imgLogo.Visible = false;
}
if (Parameters.Logovoet != null)
{
foutief = false;
imgVoet.ImageUrl = Parameters.Logovoet;
imgVoet.Visible = true;
imgVoet.Height = 140;
imgVoet.Width = 794;
}
if (!foutief) { lblAdresgegevens.Text = adresgegevens; }
#endregion
}
catch (Exception ex)
{
huidigDocument.log("DocumentToevoegen.aspx", "Page_Load", ex.Message.ToString());
}
if (!Page.IsPostBack)
{
//Huidige datum ophalen volgens het Belgisch formaat.
//Datum wordt gebruikt om de Documentdatum in te stellen en de vervaldatum.
DateTime dt = DateTime.Now;
txtDocumentDatum.Text = dt.ToString("dd-MM-yyyy");
dt = dt.AddDays(30);
txtVervaldatum.Text = Parameters.Vervaldatum;
ddlLand.SelectedValue = "20";
lblIntraCom.Text = "";
try
{
#region klanten ophalen
//Klanten invullen met de opgehaalde waardes uit een Dictionary
foreach (KeyValuePair<string, string> klant in huidigeKlant.KlantenOphalen())
{
string naam = klant.Value;
ddlKlant.Items.Add(new System.Web.UI.WebControls.ListItem(naam, naam));
}
#endregion
#region dagboeken ophalen
//Dagboeken invullen met de opgehaalde waardes uit een Dictionary
foreach (KeyValuePair<string, string> dagboeken in huidigDocument.Dagboeken())
{
//ddlDagboek.Items.Clear();
string ID = dagboeken.Key;
string omschrijving = dagboeken.Value;
ddlDagboek.Items.Add(new System.Web.UI.WebControls.ListItem(omschrijving, ID));
}
#endregion
#region postcodes ophalen
//Postcodes invullen met de opgehaalde waardes uit een Dictionary
foreach (KeyValuePair<string, string> postcode in huidigeKlant.Postcodes())
{
string ID = postcode.Key;
string gemeente = postcode.Value;
ddlGemeente.Items.Add(new System.Web.UI.WebControls.ListItem(gemeente, ID));
}
huidigDocument.DocumentNummerOpvragen(int.Parse(ddlDagboek.SelectedValue));
txtDocNr.Text = huidigDocument.documentCode + " / " + huidigDocument.huidigDocumentNummer;
#endregion
#region landen ophalen
//Landen invullen met de opgehaalde waardes uit een Dictionary
foreach (KeyValuePair<string, string> land2 in huidigeKlant.Landen())
{
string ID = land2.Key;
string land = land2.Value;
ddlLand.Items.Add(new System.Web.UI.WebControls.ListItem(land, ID));
}
huidigDocument.DocumentTitelOpvragen(int.Parse(ddlDagboek.SelectedValue));
lblDocumentTitel.Text = huidigDocument.documentTitel;
#endregion
}
catch (Exception ex)
{
huidigDocument.log("DocumentToevoegen.aspx", "Page_Load", ex.Message.ToString());
}
}
}
private void GenerateTable(int existing, int rowsCount)
{
try
{
//Alle data halen uit de PassThrough class om opnieuw een connectie te maken met SharePoint
ClientContext clientContext = ContextTokensOphalen();
Table table = Page.Form.FindControl("tblArtikels") as Table;
if (table == null)
{
table = new Table();
table.ID = "tblArtikels";
Page.Form.Controls.Add(table);
}
else
{
if (existing == 0)
{
table.Controls.Clear();
}
}
//The number of Columns to be generated
const int colsCount = 6;//You can changed the value of 3 based on you requirements
// Now iterate through the table and add your controls
for (int i = existing; i < rowsCount; i++)
{
if (!dicArtikels.ContainsKey(i))
{
Artikels artikel = new Artikels();
dicArtikels.Add(i, artikel);
}
TableRow row = new TableRow();
for (int j = 0; j < colsCount; j++)
{
TableCell cell = new TableCell();
//means the first column of the Table
if (j == 0)
{
cell.Width = 40;
//Create the CheckBox
CheckBox cb = new CheckBox();
// Set a unique ID for each CheckBox
cb.ID = "CheckBoxRow_" + i + "Col_" + j;
// Add the control to the FIRST TableCell
cell.Controls.Add(cb);
// Add the TableCell to the TableRow
row.Cells.Add(cell);
}
//2de kolom
else if (j == 1)
{
cell.Width = 60;
//Create the TextBox
TextBox tb = new TextBox();
// Set a unique ID for each TextBox
tb.ID = "TextBoxRow_" + i + "Col_" + j;
tb.Width = 40;
tb.EnableViewState = true;
tb.EnableTheming = true;
// Add the control to the TableCell
cell.Controls.Add(tb);
// Add the TableCell to the TableRow
row.Cells.Add(cell);
}
//Kolom 3
else if (j == 2)
{
cell.Width = 310;
cell.HorizontalAlign = HorizontalAlign.Right;
//Create the TextBox
TextBox tb = new TextBox();
// Set a unique ID for each TextBox
tb.ID = "TextBoxRow_" + i + "Col_" + j;
tb.Width = 290;
tb.EnableViewState = true;
tb.EnableTheming = true;
tb.TextMode = TextBoxMode.MultiLine;
// Add the control to the TableCell
cell.Controls.Add(tb);
// Add the TableCell to the TableRow
row.Cells.Add(cell);
}
//Kolom 4
else if (j == 3)
{
cell.Width = 160;
cell.HorizontalAlign = HorizontalAlign.Right;
//Create the TextBox
TextBox tb = new TextBox();
// Set a unique ID for each TextBox
tb.ID = "TextBoxRow_" + i + "Col_" + j;
//tb.TextChanged += new EventHandler(txtArtikelPrijs_TextChanged);
tb.Width = 140;
tb.EnableViewState = true;
tb.EnableTheming = true;
// Add the control to the TableCell
cell.Controls.Add(tb);
// Add the TableCell to the TableRow
row.Cells.Add(cell);
}
//Kolom 5
else if (j == 4)
{
cell.Width = 160;
cell.HorizontalAlign = HorizontalAlign.Right;
//Create the TextBox
TextBox tb = new TextBox();
// Set a unique ID for each TextBox
tb.ID = "TextBoxRow_" + i + "Col_" + j;
//tb.TextChanged += new EventHandler(txtArtikelPrijs_TextChanged);
tb.Width = 140;
tb.Enabled = false;
tb.BackColor = System.Drawing.ColorTranslator.FromHtml("#F2F2F2");
tb.TabIndex = -1;
tb.EnableViewState = true;
tb.EnableTheming = true;
// Add the control to the TableCell
cell.Controls.Add(tb);
// Add the TableCell to the TableRow
row.Cells.Add(cell);
}
//Kolom 6
else if (j == 5)
{
cell.HorizontalAlign = HorizontalAlign.Right;
cell.Width = 64;
//Create the TextBox
DropDownList ddl = new DropDownList();
// Set a unique ID for each TextBox
ddl.ID = "DropDownRow_" + i + "Col_" + j;
ddl.Width = 50;
ddl.TabIndex = -1;
ddl.EnableViewState = true;
ddl.EnableTheming = true;
ddl.Items.Clear();
//Lijst met artikelen ophalen en dropdown opvullen
List oListBTW = clientContext.Web.Lists.GetByTitle("Lijst BTWcodes");
clientContext.ExecuteQuery();
CamlQuery cQBTW = new CamlQuery();
cQBTW.ViewXml = "<View>"
+ "<Query>"
+ "</Query>"
+ "</View>";
Microsoft.SharePoint.Client.ListItemCollection btwListItem = oListBTW.GetItems(cQBTW);
clientContext.Load(btwListItem);
clientContext.ExecuteQuery();
foreach (Microsoft.SharePoint.Client.ListItem btwItem in btwListItem)
{
string btwcode = btwItem["bcCode"].ToString();
string btwpercentage = btwItem["bcBTW"].ToString();
ddl.Items.Add(new System.Web.UI.WebControls.ListItem(btwpercentage, btwcode));
}
if (i >= initNumRows && ddlBTWregime.Items.Count > 0)
{
if (ddlBTWregime.SelectedItem.Value == "Medecontractant" || ddlBTWregime.SelectedItem.Value == "intracom goederen" || ddlBTWregime.SelectedItem.Value == "intracom diensten")
{
ddl.Enabled = false;
ddl.SelectedItem.Text = "0";
ddl.BackColor = System.Drawing.ColorTranslator.FromHtml("#F2F2F2");
}
else if (ddlBTWregime.SelectedItem.Value == "BTW 6%")
{
ddl.Enabled = false;
ddl.SelectedItem.Text = "6";
ddl.BackColor = System.Drawing.ColorTranslator.FromHtml("#F2F2F2");
}
else
{
ddl.Enabled = true;
ddl.BackColor = System.Drawing.ColorTranslator.FromHtml("#FFFFFF");
}
}
// Add the control to the TableCell
cell.Controls.Add(ddl);
// Add the TableCell to the TableRow
row.Cells.Add(cell);
}
}
// And finally, add the TableRow to the Table
tblArtikels.Rows.Add(row);
}
//Sore the current Rows Count in ViewState
numOfRows = rowsCount;
}
catch (Exception ex)
{
huidigDocument.log("DocumentToevoegen.aspx", "Genereer tabel", ex.Message.ToString());
}
}
Below the .cs file i'm using to get the list items from SharePoint =>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Client;
namespace AdminCareWeb
{
public class Klanten
{
SharePointContextToken contextToken;
string accessToken;
string currentUser;
Uri sharepointUrl;
string contextTokenString;
Document logging = new Document();
#region props
public string KlantID { get; set; }
public string KlantNaam { get; set; }
public string KlantAdres { get; set; }
public string KlantAdres2 { get; set; }
public string KlantPostcode { get; set; }
public string KlantPlaats { get; set; }
public string KlantLand { get; set; }
public string KlantOndernemingsnummerVoorloopcode { get; set; }
public string KlantOndernemingsnummer { get; set; }
#endregion
//Lijst maken van alle landen uit de SharePoint lijst landen.
public Dictionary<string, string> Landen()
{
Dictionary<string, string> landenLijst = new Dictionary<string, string>();
try
{
contextToken = PassThrough.contextToken;
sharepointUrl = PassThrough.sharepointUrl;
accessToken = PassThrough.accessToken;
ClientContext clientContext = TokenHelper.GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken);
// Lijst met Landen ophalen en dropdown vullen
List oListLanden = clientContext.Web.Lists.GetByTitle("Lijst landen");
clientContext.ExecuteQuery();
CamlQuery cQLand = new CamlQuery();
cQLand.ViewXml = "<View><Query></Query></View>";
Microsoft.SharePoint.Client.ListItemCollection landListItem = oListLanden.GetItems(cQLand);
clientContext.Load(landListItem, items => items.Include(
item => item["ID"],
item => item["LDnaam"]));
clientContext.ExecuteQuery();
foreach (Microsoft.SharePoint.Client.ListItem landItem in landListItem)
{
string ID = landItem["ID"].ToString();
string landNaam = landItem["LDnaam"].ToString();
landenLijst.Add(ID, landNaam);
}
}
catch (Exception ex)
{
logging.log("Klanten.cs", "Landen ophalen", ex.Message.ToString());
}
return landenLijst;
}
//Lijst maken van alle postcodes uit de SharePoint lijst postcodes en gemeentes.
public Dictionary<string, string> Postcodes()
{
Dictionary<string, string> postcodesLijst = new Dictionary<string, string>();
try
{
contextToken = PassThrough.contextToken;
sharepointUrl = PassThrough.sharepointUrl;
accessToken = PassThrough.accessToken;
ClientContext clientContext = TokenHelper.GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken);
//Lijst met postcodes ophalen en dropdown opvullen
List oListPostcodes = clientContext.Web.Lists.GetByTitle("Lijst postcodes");
clientContext.ExecuteQuery();
CamlQuery cQPostcodes = new CamlQuery();
cQPostcodes.ViewXml = "<View>"
+ "<Query>"
+ "<OrderBy><FieldRef Name='PCgemeente'/></OrderBy>"
+ "</Query>"
+ "</View>";
//Lijst aanmaken met het resultaat van de uitgevoerde query.
Microsoft.SharePoint.Client.ListItemCollection postcodeListItem = oListPostcodes.GetItems(cQPostcodes);
clientContext.Load(postcodeListItem, items => items.Include(
item => item["ID"],
item => item["PCgemeente"]));
clientContext.ExecuteQuery();
foreach (Microsoft.SharePoint.Client.ListItem postcodeItem in postcodeListItem)
{
string ID = postcodeItem["ID"].ToString();
string gemeente = postcodeItem["PCgemeente"].ToString();
postcodesLijst.Add(ID, gemeente);
}
}
catch (Exception ex)
{
logging.log("Klanten.cs", "Postcodes ophalen", ex.Message.ToString());
}
return postcodesLijst;
}
//Lijst maken van alle landen uit de SharePoint lijst landen.
public Dictionary<string, string> KlantenOphalen()
{
Dictionary<string, string> klantenLijst = new Dictionary<string, string>();
try
{
contextToken = PassThrough.contextToken;
sharepointUrl = PassThrough.sharepointUrl;
accessToken = PassThrough.accessToken;
ClientContext clientContext = TokenHelper.GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken);
// Lijst met Landen ophalen en dropdown vullen
List oListKLanten = clientContext.Web.Lists.GetByTitle("Lijst Relaties");
clientContext.ExecuteQuery();
CamlQuery cQKlant = new CamlQuery();
cQKlant.ViewXml = "<View>"
+ "<Query>"
+ "<Where><Eq><FieldRef Name='RLtyperelatie' /><Value Type='Choice'>Klant</Value></Eq></Where>"
+ "<OrderBy><FieldRef Name='RLnaam'/></OrderBy>"
+ "</Query>"
+ "</View>";
Microsoft.SharePoint.Client.ListItemCollection klantListItem = oListKLanten.GetItems(cQKlant);
clientContext.Load(klantListItem, items => items.Include(
item => item["RLnaam"]));
clientContext.ExecuteQuery();
foreach (Microsoft.SharePoint.Client.ListItem klantItem in klantListItem)
{
string klantNaam = klantItem["RLnaam"].ToString();
klantenLijst.Add(klantNaam, klantNaam);
}
}
catch (Exception ex)
{
logging.log("Klanten.cs", "Klanten ophalen", ex.Message.ToString());
}
return klantenLijst;
}
}
}
Anyone have some suggestions to speed up. Well the problem is now it takes 7 -8 seconds before the page is showing up. Postbacks takes 3-5 seconds.

display items inside a session variable inside a repeater?

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();
}

Categories

Resources