Foreach loop in Aspx page how to add checkbox and label - c#

Foreach loop in Aspx page how to add checkbox and label values from datatable . Recieve all ticked checkbox value.
I have written this code in aspx page not in aspx.cs .
<% foreach (Employee myEmp in _empList) {
empName = myEmp.ToString(); %>
<div class="abc">
<div class="pqr">
<asp:Label Text="<% empName %>" runat="server" ID="lblEmpName"></asp:Label></label>
</div>
<div class="xyz">
<asp:CheckBox ID="chkBox" Checked="false" runat="server" />
</div>
</div>
<% } %>

I think you're just missing the : or = for the label. <% should be <%:. Use : to encode any html and avoid js injection. More info on = vs :
<% foreach (Employee myEmp in _empList) {
empName = myEmp.ToString(); %>
<div class="abc">
<div class="pqr">
<asp:Label Text="<%: empName %>" runat="server" ID="lblEmpName"></asp:Label>
</div>
<div class="xyz">
<asp:CheckBox ID="chkBox" Checked="false" runat="server" />
</div>
</div>
<% } %>

You can do something like this:
List<user> userList = new List<user>();
foreach (user usr in userList)
{
PlaceHolder1.Controls.Add(new CheckBox()
{
ID = "cb_"+usr.UserId,
Text = usr.Name,
});
}

I think the best way to add controls dynamically to asp.net page is oninit page-event.
you should try something like this.
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
/*LinkButton lb = new LinkButton();
lb.ID = "lbAddFilter";
pnlFilter.Controls.Add(lb);
lb.Text = "Add Filter";
lb.Click += new EventHandler(lbAddFilter_Click);*/
// regenerate dynamically created controls
foreach ( var employee in employeeList)
{
Label myLabel = new Label();
// Set the label's Text and ID properties.
myLabel.Text = "Label" + employee.Name.ToString();
myLabel.ID = "Label" + employee.ID.ToString();
CheckBox chkbx = new CheckBox();
chkbx.ID = "CheckBox" + employee.ID.ToString();
chkbx.Text = "Label" + employee.Name.ToString();
MyPanel.Controls.Add(myLabel);
MyPanel.Controls.Add(chkbx);
}
}

Related

How to get the hidden field value for a specific repetition within a repeator in ASP .net?

Here is my ASPX markup to display all the products available from the database, and allow the user to view details and add to cart:
<%# Page Title="" Language="C#" MasterPageFile="~/Site1.Master" AutoEventWireup="true" CodeBehind="home.aspx.cs" Inherits="WADAssignment.WebForm1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<form runat="server" >
<section class="py-5">
<div class="container px-4 px-lg-5 mt-5">
<div class="row gx-4 gx-lg-5 row-cols-2 row-cols-md-3 row-cols-xl-4 justify-content-center">
<asp:Repeater ID="RepeaterHome" runat="server">
<ItemTemplate>
<div class="col mb-5">
<div class="card h-100">
<!-- Product image-->
<img class="card-img-top" width="205.99px" height="205.99px" src="data:image/jpg;base64,<%# #Convert.ToBase64String((byte[])(Eval("prod_photo"))) %>" alt="..." />
<!-- Product details-->
<div class="card-body p-4">
<div class="text-center">
<!-- Product name-->
<asp:HiddenField ID="prodId" Value='<%# Eval("prod_id") %>' runat="server" />
<h5 class="fw-bolder"><%# Eval("prod_name") %></h5>
<!-- Product price-->
RM <%# Eval("prod_price") %><br/>
<%# Eval("prod_desc") %>
</div>
</div>
<!-- Product actions-->
<div class="card-footer p-4 pt-0 border-top-0 bg-transparent">
<div class="text-center">
<asp:Button CssClass="btn btn-outline-dark mt-auto" ID="Button2" runat="server" Text="View Details" PostBackUrl='<%# "productDetails.aspx?id=" + Eval("prod_id") %>'/>
</div><br />
<div class="text-center">
<asp:Button CssClass="btn btn-outline-dark mt-auto" ID="Button1" runat="server" Text='<%# Convert.ToInt32(Eval("prod_quantity")) > 0 ? "Add to Cart" : "Sold out" %>' Enabled='<%# Convert.ToInt32(Eval("prod_quantity")) > 0 ? true : false %>' OnClick="Button1_Click" />
</div>
</div>
</div>
</div>
</ItemTemplate>
</asp:Repeater>
</div>
</div>
</section>
</form>
</asp:Content>
This is the onclick function for the add to cart button, however with my current implementation of going through the repeater item list, the biggest prodId will always be selected, instead of the respective one, and then causing a SQL error.
protected void Button1_Click(object sender, EventArgs e)
{
HiddenField hidden = null;
foreach (RepeaterItem item in RepeaterHome.Items)
{
hidden = (HiddenField)item.FindControl("prodId");
}
int prodId = Convert.ToInt32(hidden.Value);
String id = Session["id"].ToString();
string strCon = ConfigurationManager.ConnectionStrings["WebConfigConString"].ConnectionString;
using (SqlConnection con = new SqlConnection(strCon))
{
string strCart = "INSERT INTO CART_ITEM (id, prod_id, quantity) values (#id, #prod_id, #quantity)";
string strUpdateProd = "UPDATE PRODUCT SET PROD_QUANTITY = PROD_QUANTITY - 1 WHERE PROD_ID = #prod_id";
using (SqlCommand cmdCart = new SqlCommand(strCart, con))
{
try
{
con.Open();
cmdCart.Parameters.AddWithValue("#id", id);
cmdCart.Parameters.AddWithValue("#prod_id", prodId);
cmdCart.Parameters.AddWithValue("#quantity", 1);
SqlDataReader dtrCart = cmdCart.ExecuteReader();
dtrCart.Close();
con.Close();
using (SqlCommand cmdUpdateProd = new SqlCommand(strUpdateProd, con))
{
con.Open();
cmdUpdateProd.Parameters.AddWithValue("#prod_id", prodId);
SqlDataReader dtrUpdateProd = cmdUpdateProd.ExecuteReader();
dtrUpdateProd.Close();
con.Close();
}
} catch (SqlException)
{
Response.Write("<script>alert('Item already in cart!')</script>");
}
}
}
}
This screenshot is showing my web page:
My product page
Ok, you want the current item you click on. But you ahve a loop (for each) like this:
foreach (RepeaterItem item in RepeaterHome.Items)
{
hidden = (HiddenField)item.FindControl("prodId");
}
the above will loop for each item, and then when done it will ALWAYS be the last item.
You want to JUST get the current ONE item that you clicked on, not loop (for each) as you have above.
So, your code can be like this (example code).
protected void Button1_Click(object sender, EventArgs e)
{
HiddenField hidden = null;
// get row click information
Button MyBtn = (Button)sender;
RepeaterItem MyRepeaterItem = (RepeaterItem)MyBtn.NamingContainer;
hidden = (HiddenField)MyRepeaterItem.FindControl("prodId");
int prodId = Convert.ToInt32(hidden.Value);
String id = Session["id"].ToString();
string strCon = ConfigurationManager.ConnectionStrings["WebConfigConString"].ConnectionString;
using (SqlConnection con = new SqlConnection(strCon))
{
string strCart = #"INSERT INTO CART_ITEM (id, prod_id, quantity)
values (#id, #prod_id, #quantity)";
string strUpdateProd = #"UPDATE PRODUCT SET PROD_QUANTITY = PROD_QUANTITY - 1
WHERE PROD_ID = #prod_id";
using (SqlCommand cmdCart = new SqlCommand(strCart, con))
{
try
{
con.Open();
cmdCart.Parameters.Add("#id", SqlDbType.Int).Value = id;
cmdCart.Parameters.Add("#prod_id", SqlDbType.Int).Value = prodId;
cmdCart.Parameters.Add("#quantity", SqlDbType.Int).Value = 1;
cmdCart.ExecuteNonQuery();
cmdCart.Parameters.Clear();
cmdCart.CommandText = strUpdateProd;
cmdCart.Parameters.Add("#prod_id", SqlDbType.Int).Value = prodId;
cmdCart.ExecuteNonQuery();
}
catch (SqlException)
{
Response.Write("<script>alert('Item already in cart!')</script>");
}
}
}
}
Now, above will do the update and add to the cart. But, we have good chance that we want to check if the item is already in the cart, and not allow to add again. (or just increase the qty if they choose again - not sure which choice you want). So, the above will allow adding again and again. So, before we run the above? We should find out if the item already in the cart.
(that part is missing, and was not part of your question).

ASP.NET Passing asp:Repeater value to asp:Button CssClass attribute

I have a payment method repeater that contains a button. We have new button styles that need to be applied. The new button style changes based on a btnMode setting in the database which is set to a string representing a CSS class selector. The CSS works fine.
I put this in the ASPX page:
<asp:Button ID="btnEdit"
runat="server"
ClientIDMode="Static"
CssClass='<%# Eval("btnMode") %>'
Text="edit"
CommandName="ChangePaymentProfile"
CommandArgument='<%# Eval("PaymentSourceId") + "|" + Eval("AuthNetPaymentProfileId")%>' />
In the ASPX.cs
//Command Button Clicked: Change Payment Method
else if (e.CommandName.ToLower().Equals("changepaymentprofile"))
{
hdChangeYN.Value = "Y";
showAddPaymentForm();
//display billing address of selected card
hsParams.Add("CustomerId", User.Identity.Name);
hsParams.Add("PaymentSourceId", strPaymentSourceId);
DataTable dt = DbHelper.GetDataTableSp("234_accountAddress__ByPaySourceId", hsParams);
if (dt.Rows.Count > 0)
{
tbFistName.Text = dt.Rows[0]["FirstName"].ToObjectString();
tbLastName.Text = dt.Rows[0]["LastName"].ToObjectString();
inputAddress1.Text = dt.Rows[0]["Address"].ToObjectString();
inputAddress2.Text = "";
string strCountryCd = dt.Rows[0]["CountryCd"].ToObjectString();
ddlCountry_Update(strCountryCd); //Update Country & State DDL because Country can be a foreign country
ddlCountry.SelectedValue = strCountryCd;
inputCity.Text = dt.Rows[0]["City"].ToObjectString();
ddlState.SelectedValue = dt.Rows[0]["StateProvinceId"].ToObjectString();
inputZipcode.Text = dt.Rows[0]["Zipcode"].ToObjectString();
ddlCardType.SelectedValue = dt.Rows[0]["CardType"].ToObjectString();
}
}
When I load the page in the browser the <%# Eval("btnMode") %> does not get resolved to a value. I see this when I open the inspector:
<input
id="btnEdit"
class="<%# Eval("btnMode") %>"
type="submit"
name="ctl00$ctl00$ContentPlaceHolderFront$ContentPlaceHolderFront$rptList$ctl01$btnPrimary"
value=""
onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$ctl00$ContentPlaceHolderFront$ContentPlaceHolderFront$rptList$ctl01$btnPrimary", "", true, "", "", false, false))" >
It is important to point out that this attribute CommandArgument='<%# Eval("PaymentSourceId") %>' does work, and btnMode does contain valid data.
As I wrote in a comment, not all properties in Asp.Net controls can be databound. CssClass is one that cannot be databound.
To get around this, you can add an OnItemDataBound event handler to the repeater where the Button is. In the event handler you can then user the e.Item.DataItem to get the value you want and set it as the CssClass on the button. Sample code:
<asp:Repeater ID="RepeaterTest" runat="server" OnItemDataBound="RepeaterTest_ItemDataBound">
<ItemTemplate>
<div>
<asp:Button ID="TestButton" runat="server" Text='<%# Eval("someText") %>'/>
</div>
</ItemTemplate>
</asp:Repeater>
and code behind:
protected void Page_Load(object sender, EventArgs e)
{
var testData = Enumerable.Range(1, 10).Select(i => new { someText = "Button " + i.ToString() }).ToList();
RepeaterTest.DataSource = testData;
RepeaterTest.DataBind();
}
protected void RepeaterTest_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
dynamic foo = e.Item.DataItem;
((Button)e.Item.FindControl("TestButton")).CssClass = foo.someText;
}

Hide a column in one repeater based on the value of a checkbox in another

I have a product listing page which has several divs set up to look like a table. The product listing is inside one of two repeaters. The outer most repeater (called locationRepeater) sets the location area name for each batch of products (Public Areas, Showers and Sinks), and the second repeater (areaRepeater) generates the listing of products (I can't go back and redo the code so I only use 1 repeater--there's no time for that):
<asp:Repeater ID="locationRepeater" runat="server" OnItemDataBound="SetInner">
<ItemTemplate>
<div class="LocationName">
<%# Eval("SecOpen") %><%# Eval("LocationName")%> <%# Eval("SecClose") %>
</div>
<asp:Repeater ID="areaRepeater" runat="server">
<HeaderTemplate>
<div class="headerRow">
<div class="header">
<div class="thumb"><p></p></div>
<div class="headerField name"><p class="hField">Product</p></div>
<div class="headerField sku"><p class="hField">GOJO SKU</p></div>
<div class="headerField size"><p class="hField">Size</p></div>
<div class="headerField case"><p class="hField">Case Pack</p></div>
<div class="headerField qty"><p class="hField">Add to Shopping List</p></div>
</div>
</div>
</HeaderTemplate>
<ItemTemplate>
<asp:placeholder id="LocationAreaHeader" runat="server" visible='<%# (Eval("AreaName").ToString().Length == 0 ? false : true) %>' ><h3> <%# Eval("AreaName") %></h3></asp:placeholder>
<asp:placeholder id="ProductTable" runat="server" visible='<%# (Eval("ProductName").ToString().Length == 0 ? false : true) %>' >
<div class="table">
<div class="row">
<div class="thumb"><%# Eval("Charm") %></div>
<div class="field name"><p class="pField"> <%# Eval("ThumbOpen") %><%# Eval("ProductName") %><%# Eval("ThumbClose") %></p> </div>
<div class="field sku"><p class="pField"> <%# Eval("Sku") %> </p></div>
<div class="field size"><p class="pField"> <%# Eval("Size") %></p></div>
<div class="field case"><p class="pField"> <%# Eval("CasePack") %> </p></div>
<asp:PlaceHolder runat="server" ID="ShoppingField">
<div class="field qty"><p class="pField"> <asp:checkbox id="LineQuantity" runat="server" /></p></div>
</asp:PlaceHolder>
</div>
</div>
<asp:Label id="productID" text='<%# Eval("productID") %>' visible="false" runat="server" />
</asp:placeholder>
<!-- Stored values -->
<asp:Label id="SkuID" runat="server" text='<%# Eval("SkuID") %>' visible="true" />
<asp:Label id="masterSku" runat="server" text='<%# Eval("masterSku") %>' visible="false" />
<asp:Label id="masterName" runat="server" text='<%# Eval("masterName" ) %>' visible="false" />
<asp:Label ID="test" visible="false" runat="server" text='<%# Eval("AreaID") %>' />
</ItemTemplate>
</asp:Repeater>
<asp:Label ID="refID" visible="false" runat="server" text='<%# Eval("LocationID") %>' />
</ItemTemplate>
</asp:Repeater>
In the template for the product listing page is a checkbox called "Shopping Disabled" which is meant to hide a column from the areaRepeater's product listing table if it's checked. However, the "Shopping Disabled" checkbox exists inside the first repeater (locationRepeater). How can I hide the "Add to Shopping" column based on a value found inside the creation of the locationRepeater?
private void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Item CurrentItem = Sitecore.Context.Item;
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"));
locations.Columns.Add("SecOpen", Type.GetType("System.String"));
locations.Columns.Add("SecClose", Type.GetType("System.String"));
string secColor = "";
if (CurrentItem.TemplateName == "gojoProductLocation")
{
Sitecore.Data.Fields.CheckboxField checkbox = CurrentItem.Fields["Active"];
if (checkbox.Checked)
{
DataRow dr = locations.NewRow();
dr["LocationName"] = CurrentItem.Fields["Header"].Value;
dr["LocationID"] = CurrentItem.ID.ToString();
locations.Rows.Add(dr);
}
}
else
{
Item HomeItem = ScHelper.FindAncestor(CurrentItem, "gojoMarket");
if (HomeItem != null)
{
Item ProductGroup = HomeItem.Axes.SelectSingleItem(#"child::*[##templatename='gojoMarketOfficeBuildigProductMap']/*[##templatename='gojoProductList']");
if (ProductGroup != null)
{
//this is where I can get the value of the "Shopping Disabled" checkbox
Sitecore.Data.Fields.CheckboxField checkBox = ProductGroup.Fields["Shopping Disabled"];
if (checkBox.Checked)
{
submitBtn.Visible = false;
}
Item[] LocationList = ProductGroup.Axes.SelectItems(#"child::*[##templatename='gojoProductLocation' and #Active = '1']");
if (LocationList != null)
{
foreach (Item LocationItem in LocationList)
{
DataRow dr = locations.NewRow();
secColor = LocationItem.Fields["Section Color"].Value;
dr["SecOpen"] = "<h1 style='padding-top: 10px; background-color:#" + secColor + "'>";
dr["LocationName"] = LocationItem.Fields["Header"].Value;
dr["LocationID"] = LocationItem.ID.ToString();
dr["SecClose"] = "</h1>";
locations.Rows.Add(dr);
}
}
}
}
}
locationRepeater.DataSource = ds;
locationRepeater.DataMember = "locations";
locationRepeater.DataBind();
if (locationRepeater.Items.Count == 0)
{
//show message -RTE field on product map page
Literal lit = (Literal)FindControl("Return");
}
}
}
//This function populates the second repeater, which has the "Add to Shopping" column I want to hide
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");
string secColor = "";
areas.Columns.Add("AreaName", Type.GetType("System.String"));
areas.Columns.Add("Sku", Type.GetType("System.String"));
areas.Columns.Add("Large Image", Type.GetType("System.String"));
areas.Columns.Add("Charm", 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("CasePack", 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"));
areas.Columns.Add("ThumbOpen", Type.GetType("System.String"));
areas.Columns.Add("ThumbClose", 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"] = "N/A";
}
Sitecore.Data.Fields.XmlField fileField = ChildItem.Fields["Charm"];
newRow["Charm"] = "<image src=\"" + ScHelper.GetCorrectFilePath(fileField) + "\" border=\"0\" alt=\"\">";
newRow["Sku"] = MasterProduct.Fields["SKU"].Value;
newRow["productID"] = ChildItem.ID.ToString();
newRow["CasePack"] = MasterProduct.Fields["Case Pack"].Value;
newRow["Large Image"] = "";
try
{
string prodNameLink = "";
Item MasterProductName = db.Items[MasterProduct.Fields["Complete Product Name"].Value];
string prodImg = MasterProduct.Fields["Large Image"].Value;
if (prodImg != "")
{
Sitecore.Data.Fields.XmlField productImg = MasterProduct.Fields["Large Image"];
prodNameLink = MasterProduct.Fields["Large Image"].Value;
newRow["ThumbOpen"] = string.Format("<a href=\"{0}\" class=\"fancybox\" title=\"{1}\" rel=\"image\">", ScHelper.GetCorrectFilePath(productImg), MasterProduct.Fields["SKU"].Value);
newRow["ThumbClose"] = "</a>";
}
if (MasterProductName != null)
{
newRow["ProductName"] = MasterProductName.Fields["Complete Name"].Value;
}
areas.Rows.Add(newRow);
}
catch (Exception x)
{
Response.Write(x.Message.ToString() + "<br />");
}
}
}
}
}
areaRepeater.DataSource = dset;
areaRepeater.DataMember = "areas";
areaRepeater.DataBind();
}
}
}
}
There are likely better ways to handle this but since you are already using the approach of storing data in hidden fields (ex: "refID") you can take this same approach for the "Shopping Disabled" field.
Add a new Column to your DataTable in your Page_Load:
locations.Columns.Add("ShoppingDisabled", Type.GetType("System.String"));
Add the shopping disabled data to this Column in your Page_Load:
dr["ShoppingDisabled"] = checkBox.Checked;
locations.Rows.Add(dr);
Add the hidden label to your User Control:
<asp:Label ID="ShoppingDisabled" visible="false" runat="server" text='<%# Eval("ShoppingDisabled") %>' />
Grab the label in your SetInner() method:
Label lblShoppingDisabled = (Label)e.Item.FindControl("ShoppingDisabled");
Add logic to your SetInner() method or the user control to hide what you ever you need to hide based on lblShoppingDisalbed.Text.
If I am understanding correctly, you are looking to hide a column which is represented as a div?
If this is the case add the attribute runat="server" to your div that you wish to hide.
In the code behind you will then be able to use findcontrol to find the checkbox, areaRepeater, and the div and then you will be able to set the visibility of the div based on your checkbox.
It would be something like:
foreach(Repeater rep in locationRepeater.Items)
{
Repeater areaRepeater = (Repeater)rep.FindControl("areaRepeater");
CheckBox disable = (CheckBox)rep.FindControl("checkboxid");
foreach(Repeater areaRep in areaRepeater.Items)
{
HtmlGenericControl div = (HtmlGenericControl)areaRep.FindControl("div");
div.Visible = disable.Checked;
}
}
Ok, so, what I ended up doing was creating a function that got the value of the "Shopping Disabled" checkbox and set a boolean variable to either true or false based on that. I then called this function inside the "visible" property of both the "Add To Shopping List" header and the checkbox field in the product listing table. This allowed me to show/hide that column as needed. Thanks for the suggestions, though!

Unable to render html in ascx control page

Here is my ascx control page code
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="Menu.ascx.cs" Inherits="CrossQueue.Web.Menu" %>
<asp:Label ID="lblMenu" runat="server"></asp:Label>
Here is my c# code
private void CreateMenu()
{
StringBuilder menuHtml = new StringBuilder();
int profileId = 0;
MenuBL menuManager = new MenuBL();
DataTable dtMenu = null;
if (Session["USR_ID"] != null)
{
profileId = Convert.ToInt32(Session["USR_PROFILE"]);
dtMenu = menuManager.GetAllMenuItemsForProfile(profileId);
if (dtMenu != null && dtMenu.Rows.Count > 0)
{
menuHtml.Append("<table id='tblMenu' cellpadding='0' cellspacing='0' width='939' border='0' align='center'>");
menuHtml.Append("<tr>");
menuHtml.Append("<td align='left'>");
menuHtml.Append(Convert.ToString(Session["USR_USERNAME"]));
menuHtml.Append("</td>");
menuHtml.Append("<td width='739' valign='middle' align='right' style='height: 30px;'>");
foreach (DataRow dr in dtMenu.Rows)
{
if (dr["MenuName"].ToString() == "Profile")
{
menuHtml.Append("<img src='/images/home_icon.jpg' width='25' height='25' align='middle' /><a href='AllProfile.aspx>Profile</a> ");
}
else if (dr["MenuName"].ToString() == "User")
{
menuHtml.Append("<img src='/images/home_icon.jpg' width='25' height='25' align='middle' /><a href='AllUsers.aspx>User</a> ");
}
}
menuHtml.Append("</td>");
menuHtml.Append("</tr>");
menuHtml.Append("</table>");
}
lblMenu.Text = menuHtml.ToString();
}
}
When i load the page i only see a html code printed as text and not rendering.Can any one point out what may be wrong
You could use a literal instead of a label.
See this
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.literal.aspx
You can make a div server accessible by assigning ID and setting runat="server" instead of label and set its InnerHTML = menuHtml.ToString();
<div id="div1" runat="server" ></div>
div1.InnerHTML = menuHtml.ToString();
change the Label
<asp:Label ID="lblMenu" runat="server"></asp:Label>
to Literal as
<asp:Literal ID="lblMenu" runat="server" EnableViewState="false"></asp:Literal>

Finding controls in repeater on commandargument

I have a repeater:
<asp:Repeater ID="rpt_Items" OnItemCommand="rpt_Items_ItemCommand" runat="server">
<ItemTemplate>
<div class="item">
<div class="fr">
<asp:TextBox ID="tb_amount" runat="server">1</asp:TextBox>
<p>
<%# Eval("itemPrice") %>
</p>
<asp:LinkButton ID="lb_buy" CommandName="buy" runat="server">buy</asp:LinkButton>
</div>
<asp:HiddenField ID="hdn_ID" Value='<%# Eval("itemID") %>' runat="server" />
</div>
</ItemTemplate>
</asp:Repeater>
On the repeater commandargument i want to get the textbox and the hiddenfield but how do i do this?
protected void rpt_Items_ItemCommand(object sender, RepeaterCommandEventArgs e)
{
if (e.CommandName == "buy")
{
//ADD ITEM TO CART
Response.Write("ADDED");
Product getProduct = db.Products.FirstOrDefault(p => p.ProductID == id);
if (getProduct != null)
{
CartProduct product = new CartProduct()
{
Name = getProduct.ProductName,
Number = amount,
CurrentPrice = getProduct.ProductPrice,
TotalPrice = amount * getProduct.ProductPrice,
};
cart.AddToCart(product);
}
}
}
Thanks a bunch!
You don't have to pass it through the Command Argument, you can use e.Item.FindControl() inside your rpt_Items_ItemCommand method, as in:
TextBox tb_amount = (TextBox)e.Item.FindControl("tb_amount");
HiddenField hdn_ID = (HiddenField)e.Item.FindControl("hdn_ID");

Categories

Resources