Variable does not exist in the current context - c#

I'm new to C# .NET. I would like to ask how this works... What I want is just to show an age selection from 1 to 100.
Inside the .aspx file I put this code, I used data binding for the variable listAge.
<asp:DropDownList ID="AgeDropDown" runat="server">
<%# listAge %>
</asp:DropDownList>
Here's the code-behind for it:
protected void Page_Load(object sender, EventArgs e)
{
for (int i = 1; i < 101; i++)
{
string listAge;
listAge = "<asp:ListItem>"+ i +"</asp:ListItem>";
}
}
The error shown inside the .aspx is:
Error Creating Control: AgeDropDown - Code blocks are not supported in this context.
Because of the variable listAge?
Thank you for the help!

Drop the <% %> section in .aspx and in code behind you should do something like this:
protected void Page_Load(object sender, EventArgs e)
{
AgeDropDown.Items.Clear();
for (int i = 1; i < 101; i++)
{
AgeDropDown.Items.Add(new ListItem(i.ToString(),i.ToString()));
}
}
From another point of view there are several flaws in your code:
You are generating ASP.NET tags in code behind. ASP tags are processed on the server and are rendered into html tags. You were practically inserting a tag in html, which browsers will render as simple text since it's not a valid HTML tag.
You were creating a new listAge variable on each iteration of the for loop. Even if the code would work it would display just the last item

You could use the server version of AgeDropDown.
ListItem li;
for (int i = 1; i < 101; i++)
{
li = new ListItem(i.ToString(), i.ToString());
AgeDropDown.Items.Add(li);
}

Is this in asp.net or MVC?
Probably
... <%# listAge %>
should be
... <%= listAge %>

Related

Dynamically add div in .aspx page

I'm looking for a JavaScript-free way to dynamically add div elements inside a certain element of an aspx web page according to data passed to i.
I'm looking for something similar to razor c# where you can even create loops and write c# code that directly effects the content of the page.
It appears that razor c# doesn't work unless the page is a .cshtml page, so I'm kinda lost here since I don't want to use JavaScript.
Is there a better approach to it?
Say, below is the placeholder div
<div id = "maindiv">
<asp:PlaceHolder ID ="maindivs" runat="server">
</asp:PlaceHolder>
</div>
Then you may add divs to your placeholder div like below
protected void addmainDiv(int m)
{
for(int i = 0; i< m; i++)
{
System.Web.UI.HtmlControls.HtmlGenericControl newdivs = new System.Web.UI.HtmlControls.HtmlGenericControl("DIV");
newdivs.Attributes.Add("class", "maindivs");
newdivs.ID = "createDiv";
newdivs.InnerHtml = " I'm a div, from code behind ";
maindivs.Controls.Add(newdivs);
}
}
If you want to create HTML dynamically in .aspx then you can create your html code in your .cs (backend file)
string htmlAsStringToShow = "<div>" + variable + "</div>";
Then show its content in your .aspx page like this :
<%= htmlAsStringToShow %>

How to modify the content and create many instances for a dynamic user control?

I need to use a User Control many times in the same page.aspx
I am working with visual studio 2012 and asp.net 4.0 I trying to do many graph that receives different parameter each one.
I have an user control.ascx that has code behind control.ascx.cs with a function
public void myTask(string myParameter)
I have a page.aspx with a panel
<asp:Panel ID="Panel1" runat="server">
</asp:Panel>
I had a code behind page.aspx.cs with
protected void Page_Load(object sender, EventArgs e)
{
UserControl cuc = (UserControl)LoadControl("~/cmmon/userCntrol/myusercontrol.ascx");
Panel1.Controls.Add(cuc);
My code shows nice for just one graphic.
I am willing to create many instances for my user Control and call each function from the page.aspx int the behind code page.aspx.cs like
myTask(myParameter);
with different parameter for each one. How do I do?
You can create multiple in a loop. Make sure to give each an unique ID.
for (int i = 0; i < 5; i++)
{
WebUserControl1 cuc = (WebUserControl1)LoadControl("~/WebUserControl1.ascx");
cuc.ID = "Control" + i;
Panel1.Controls.Add(cuc);
}
Then you can locate the control somewhere else in the code based on that ID.
WebUserControl1 uc = Panel1.FindControl("Control3") as WebUserControl1;
I found and resolve two issues: 1) how to send parameters to a control object. and 2) how to reference a control in another c# page.
1) To send parameters to a control object I have to define variables to accept the values of the parameters, it is done in the object control by:
using System.Web.UI.WebControls;
public partial class myControl : System.Web.UI.UserControl
{
public string variable { get; set; }
public void start(string parameter)
{
variable = parameter;
}
}
2) To reference a control in another c# page. in the page directive should be:
<%# Reference Control="~/cmmon/userCntrol/myControl.ascx" %>
Then, as VDWWD answer, in your code behind you can include an object like:
for (int i = 0; i < 5; i++)
{
WebUserControl1 cuc = (WebUserControl1)LoadControl("~/WebUserControl1.ascx");
cuc.ID = "Control" + i;
Panel1.Controls.Add(cuc);
}
And call the function as I needed:
cuc.myTask(myParameter);
Then:
for (int i = 0; i < 5; i++)
{
WebUserControl1 cuc = (WebUserControl1)LoadControl("~/WebUserControl1.ascx");
cuc.ID = "Control" + i;
Panel1.Controls.Add(cuc);
cuc.myTask(myParameter);
}

Creating ASP.NET controls from C# Code Behind error

Please consider the following:
code behind:
public void InitiateTable()
{
Controls.Add(new LiteralControl("<table class=\"table table-invoice\" >")); //Line that gave me error
...
Controls.Add(new LiteralControl("</table>"));
}
on my ASP.Net page:
<% InitiateTable(); %>
When I run the code, it gives me an error saying:
The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
Can someone please explain what I have done wrong?
Thank you.
Note Changed LiteralControl to Control as suggested in comment.
You cannot modify the controls collection where the container contains <% %> code blocks as the error message tells you. Controls.Add will modify the controls collection. To get around this:
In your aspx page change
<% InitiateTable(); %>
to
<asp:Literal runat="server" id="mytable" />
then in your page load method, add a call to InitiateTable()
then in your InitiateTable() method change your code to something like this:
public void InitiateTable()
{
var literalControlValue = new StringBuilder();
literalControlValue.Append("<table class=\"table table-invoice\" >");
...
literalControlValue.Append("</thead>"));
mytable.Text = literalControlValue.ToString();
}
Controls.Add(new LiteralControl("<table class='table table-invoice'>"));
The issue is when you use Controls you are referencing the Page itself rather than the area you call InitiateTable.
If you're inserting controls into this area, this is what a Placeholder is for:
<asp:Placeholder id="phTable"></Placeholder>
Then in your Page_Load or some other event code:
private void Page_Load(object sender, System.EventArgs e)
{
phTable.Controls.Add(new LiteralControl("<table class=\"table table-invoice\" >"));
phTable.Add(new LiteralControl("</thead>"));
}

Render dynamic # of HTML controls in aspx page like #Razor?

I know we can put a placehold on aspx page, then add controls dynamically from backend code. Is there a way in aspx page that is similar to #razor engine that we can add html control directly in aspx page?
<%
int count = GetImageCount();
for (int k = 0; k < count; k++)
{
string id = "img_" + k.ToString();
%>
<asp:Image runat="server" ImageAlign="Middle" />
<%
}
%>
We can use above code to add multiple Image control in aspx page, but how can we set them with different id and src?
Or, we can not do this in aspx directly?
thanks
You cannot set ID for server controls dynamically. Also, as far as I am aware of, setting ImageUrl direclty in aspx for the control in for loop, like in your code, might not be possible - you should probably take a look and asp:Repeater control.
To achieve what you want, you might find useful this piece of code, using HTML <img> control (as #Grundy suggested), instead of asp:Image control:
<% int count = 5;
for (int i = 0; i < count; i++)
{
string id = "id_" + i;
string imageUrl = "/Images/img_" + i;
%>
<img id="<%=id%>" src="<%=imageUrl%>"/>
<%
}
%>

method firing twice during pageload in asp.net

I know such questions are asked already on SO, and i also went through most of them but no one satisfied me, so i am posting mine one. Attached is my code. actually i am building a jquery gallery from code from databale. see the code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DisplayHotProducts();
}
}
private void DisplayHotProducts()
{
var dt = ProductData.GetAllHotProducsts();
if (dt != null && dt.Rows.Count > 0)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine(" <div id='spotlight_products' class='widget_box center_box'>");
sb.AppendLine("<div class='wintitle'>");
sb.AppendLine(" <div class='inner_wintitle'>");
sb.AppendLine(" Hot Products</div></div>");
sb.AppendLine("<div class='winbody'>");
sb.AppendLine("<div class='mall_focus' id='mall_focus'>");
sb.AppendLine("<a id='bp_carousel_prev'>prev</a>");
sb.AppendLine("<a id='bp_carousel_next'>next</a>");
sb.AppendLine("<div id='bp_carousel'>");
sb.AppendLine(" <div class='carousel_list'>");
for (int i = 0; i < dt.Rows.Count; i=i+5)
{
sb.AppendLine(" <div class='product_list'>");
sb.AppendLine("<div class='bestproduct_wrapper'> <div class='bestproduct'>");
sb.AppendLine(" <div class='icon_best'></div>");
sb.AppendLine("<ul>");
sb.AppendLine(" <li class='best_Img'><span></span><a href='#' target='_blank'> ");
sb.AppendLine(string.Format(" <img src='{0}' width='200' height='200' /></a></li>", dt.Rows[i]["ImagePath"]));
sb.AppendLine("</ul>");
sb.AppendLine(" <p class='product_name'>");
sb.AppendLine(string.Format("<a href='Products/{0}' target='_blank'>{1}</a></p>", dt.Rows[i]["Id"], dt.Rows[i]["Name"]));
sb.AppendLine("</div></div>");
for (int j = i+1; j <= 4; j++)
{
sb.AppendLine("<div class='product_item'>");
sb.AppendLine("<ul><li class='product_Img'>");
sb.AppendLine(string.Format("<a href='Products/{0}'><img src='{1}' width='70' height='70'/></a>", dt.Rows[j]["Id"], dt.Rows[j]["ImagePath"]));
sb.AppendLine("</li></ul>");
sb.AppendLine(string.Format("<p class='product_name'><a href='Products/{0}'>{1}</a></p>", dt.Rows[j]["Id"], dt.Rows[j]["Name"]));
sb.AppendLine("</div>");
}
}
sb.AppendLine(#" </div></div></div></div></div>");
ltlHotProducts.Text = sb.ToString();
}
}
}
My code behind has the above code only and the page load is firing twice.
Also this is code behind of a usercontrol, placed on a page where i have 3 more similar control performing similar functionalities that is , building jquery slideshows from code behind. But the above two user controls has some issues with the img tags as some of them are missing images. Also the page on which the user controls are placed has a master page. Now please suggest me the solution.
So the heirarchy is something like this:
Master Page (master) -> Content Page (aspx) -> Has->3 UserControls (ascx)
I have typically seen two reasons for the PageLoad to fire twice - First, if you have an img tag that doesn't have a src attribute, IE and Chrome will both request the page again, which causes the event to fire again. Second, if the event is wired up more than once, it'll fire more than once; Typically I've seen this happen when the code behind includes the event wireup code (eg, this.PageLoad += ... PageLoad) and the page directive AutoEventWireup=True is included in the aspx file.

Categories