I have an ASP.NET link button that I need to add both text and an image to I thought I would be able to just add the image to the button using Controls.Add but no dice.
Here is what I have so far:
foreach (var entity in metadata.Meta.Where(e => e.ReportableObject == true))
{
LinkButton lb = new LinkButton();
string iconpath = "~/images/search/" + entity.ClassName + ".png";
lb.CssClass = "entityIcon";
lb.Controls.Add(new Image { ImageUrl = iconpath , CssClass = "imgSize"});
lb.Text = entity.ClassName;
entityHolder.Controls.Add(lb);
}
When the control renders I see the text but I'm not even getting an image container rendered. I thought it might have been the path to the image but even when I tried to map to a image from an existing site using the full qualified path nothing would render.
Edit: For clarification there are no asp.net controls in the main page (link or image) this for loop is iterating a collection and creating the controls at runtime. The last line entityHolder is a ASP.NET panel that the buttons are added to.
Can someone help me understand what I am doing wrong if this is even possible. I have to use a LinkButton and not an ImageButton as I need to render both text and image.
Cheers
You would have to do it manipulating the Text property of the control to also render the <img tag for example:
foreach (var entity in metadata.Meta.Where(e => e.ReportableObject == true))
{
LinkButton lb = new LinkButton();
string iconpath = ResolveClientUrl("~/images/search/" + entity.ClassName + ".png");
lb.CssClass = "entityIcon";
lb.Text = string.Format(#"image <img src=""{0}"" class=""{1}"" />",iconpath,"imgSize");
entityHolder.Controls.Add(lb);
}
Use the background css attribute instead of adding a new control.
LinkButton lb = new LinkButton;
string iconpath = "~/images/search/" + entity.ClassName + ".png";
lb.Style.Add("background", "url('" + base.ResolveUrl(iconpath) + "') left center no-repeat");
lb.CssClass = "entityIcon";
lb.Text = entity.ClassName;
entityHolder.Controls.Add(lb);
Related
Dynamically building menu items and need to call a javascript function from one of them.
function popWin(url) {
var winHandle = window.open(url, '_blank', 'width=1000,height=700,resizable=yes,top=5,left=5,scrollbars=yes,status=yes');
}
<asp:Menu ID="Menu1" runat="server" StaticDisplayLevels="8" RenderingMode="List" OnMenuItemClick="Menu1_MenuItemClick" CssClass="menu" Width="150px">
</asp:Menu>
The code behind:
string url = "/somepage.aspx";
MenuItem child = new MenuItem();
child.Text = "Some Text";
child.NavigateUrl = "javascript:popWin('" + url + "');";
//child.NavigateUrl = "javascript:window.open('somepage.aspx');";
Menu1.Items[1].ChildItems.Add(child);
Just having some trouble calling the javascript function.
The window.open will work but an extra page opens and I need more control over the window opening.
The reason this needs to be done this way is there's an iFrame on the page that's loading different pages. The RegisterStartupScript was being used in the Menu1_MenuItemClick event but it was refreshing the source of the iFrame.
Thanks for any suggestions.
UPDATE
Trying to go another route on this but just not working right:
child = new MenuItem();
string win = "/SomePage.aspx";
string script = "popWin(" + win + ");";
string text = "<span style='cursor:pointer;' onclick='" + script + "'>Some Text</span>";
child.Text = text;
child.Selectable = false;
Menu1.Items[1].ChildItems.Add(child);
After coming back to this problem and testing a span tag in html with an onclick event, the problem was simply a bit of syntax:
child = new MenuItem();
string win = "/SomePage.aspx";
string script = "popWin('" + win + "');";
string text = "<span style=\"cursor:pointer;\" onclick=\"" + script + "\">Some Text</span>";
//Below is how it should render
//<span style="cursor:pointer;" onclick="popWin('/SomePage.aspx');">Some Text</span>
child.Text = text;
child.Selectable = false;
Menu1.Items[1].ChildItems.Add(child);
Thought I would post this just in case anyone else runs into the same issue.
I am trying to dynamically create a form in asp.net and render it out on the page by performing a text replace on the rendered controls.
(I cannot just push the controls to a panel on the page, that would be the ideal situation and I wouldn't be having this problem right now)
I create a label, textbox and a button and add them all to a panel. This panel is then rendered into a string using a TextWriter, which I then to use perform my replace on my copy.
Label lbl = new Label();
lbl.Text = "Enter Amount";
lbl.Attributes.Add("style", "width:25%; vertical-align:middle;");
lbl.CssClass = "donate-label";
lbl.ID = "lblAmount";
TextBox tb = new TextBox();
tb.ID = "tbAmount";
tb.Attributes.Add("style", "padding-left:25px; width:50%;");
lbl.AssociatedControlID = tb.ID;
Button b = new Button();
b.ID = "btnDonate";
b.Text = "Make a Donation";
b.CssClass="block-btn right-arrow red-bg right";
b.Click += new EventHandler(btnDonate_Click);
b.Attributes.Add("style", "display:table-cell; margin-top:0; width:40% !important;");
Panel pnlForm = new Panel();
pnlForm.CssClass="form clearfix donate-form";
pnlForm.Attributes.Add("style", "width:70%");
pnlForm.Controls.Add(lbl);
pnlForm.Controls.Add(tb);
pnlForm.Controls.Add(b);
Now if I was to add the above panel to a panel that already existed on the page, it would work perfectly and as expected, but the control rendering is causing it to break somewhere..
TextWriter myTextWriter = new StringWriter();
HtmlTextWriter myWriter = new HtmlTextWriter(myTextWriter);
pnlForm.RenderControl(myWriter);
string body = p.Copy.Replace("##donate##", myTextWriter.ToString());
The error I get is as follows:
Unable to find control with id 'tbAmount' that is associated with the Label 'lblAmount'.
Line 146: pnlForm.RenderControl(myWriter);
If I removed the assoicatedControlID for my label it works fine, but unfortunately it renders my label as a span which isn't what I need, I need it rendered as a label with a 'for' attribute.
The easiest way is to use literal with html tags inside it
Literal lbl = new Literal();
lbl.Text = "<Label For='tbAmount' style='width:25%; vertical-align:middle;' class='donate-label' > Enter Amount </label>";
lbl.ID = "lblAmount";
by the way make the tbAmount id static so you dont get any unpredictable id for your textbox
tb.ClientIDMode= System.Web.UI.ClientIDMode.Static
I have a master page "default.master" and a content page "Store.aspx", each with their own code-behind page. In the code-behind of the master page, I am dynamically creating a label with some text in it. I want to look up the text of the label in the code-behind page for the 'Store.aspx.cs' but my code is returning 'null' controls...
In my default.master.cs on page load:
<label runat=\"server\" id=\"displayname\"><a href='MyAvatar.aspx'>" + displayName + "</a></label>
In my Store.aspx.cs on page load:
HtmlGenericControl dName = (HtmlGenericControl)Master.FindControl("displayName");
if (dName != null)
Debug.Print("dName: " + dName.InnerText);
This does NOT work... However, if I put a label directly in the default.master page like this:
<label runat="server" id="displayName">TEST</label>
Then when i load the Store.aspx, I clearly see in my Debug Output:
dName: TEST
I really need the label to be created dynamically and also need to be able to access the content of the label not only from the Store.aspx.cs but from 2 other pages as well (and potentially more in the future). Any ideas??
EDIT:
I just wanted to note that the dynamically created label is part of a larger element... The label is inside a table cell, inside a table row, inside a table, all of which is inside a literal control... What the heck, why not paste the whole thing here huh? (Label is in the 4th line)
userCP.Text = "<table width=100% border=0 cellpadding=0 cellspacing=0>" +
"<tr><td colspan=4 style=\"font-size: large\"><center><b>Welcome,</b></center></td></tr>" +
"<tr style=\"height: 5px; \"><td colspan=4></td></tr>" +
"<tr><td colspan=4><center><label runat=\"server\" id=\"displayname\"><a href='MyAvatar.aspx'>" + displayName + "</a></label></center></td></tr>" +
"<tr style=\"height: 5px; \"><td colspan=4></td></tr>" +
"<tr><td colspan=4><hr/></td></tr>" +
"<tr><td>" + leaderLink + "</td><td width=100% id=\"userCP_bones\" style=\"text-align:right; \">" + bones + "</td><td style=\"text-align:left;\"><b>/</b><a href='Store.aspx?SC=Acct' title='Click to upgrade your wallet!'>" + maxBones + "</a></td><td><center><img src='images/bone.png' alt='Bones' align='right' style=\"vertical-align:middle\"/></center></td></tr>" +
"<tr><td></td><td></td><td id='CartCount' style=\"text-align:right; text-decoration: underline; cursor:pointer; \"><a href='Checkout.aspx'>" + itemCount + "</a></td><td width=10%><center><a href='Checkout.aspx'><img src='images/cart.png' onmouseover=\"this.src='images/cart_h.png'\" onmouseout=\"this.src='images/cart.png'\" height='24' width='24' alt='Cart' align='right' style=\"vertical-align:middle; border:none\"/></a></center></td></tr>" +
"</table>";
EDIT:
Based on the first answer given, instead of a literal control for "userCP", I turned that into an ASP table and add rows/cells in the code-behind:
//Row for display name
TableRow r = new TableRow();
userCP.Rows.Add(r);
TableCell c = new TableCell();
r.Cells.Add(c);
c.ColumnSpan = 4;
Label l = new Label();
l.Text = "<center><a href='MyAvatar.aspx'>" + displayName + "</a></center>";
l.ID = "displayName";
c.Controls.Add(l);
My store.aspx.cs is still returning null when doing:
Debug.Print("Name: " + Master.FindControl("displayName"));
Even if I cast the lookup:
(HtmlGenericControl)Master.FindControl("displayName")
(Label)Master.FindControl("displayName")
You cannot add server-side control by directly manipulating page markup from code, because page is already created by that time. If you want to create controls dynamically and then access them from server-side code you need to add them to Controls collection.
You have to build your ASP.Net HtmlTable server-side control (including HtmlTableRow and table HtmlTableCell and all the related controls) thru actual server-side code and add the resulting table to the userCP with something like userCP.Controls.Add(myCreatedTable)
Just to clean up, clarify, and centralize the answers and comments:
It doesn't matter if I use the LiteralControl or the Asp:Table, the 'displayName' I need is now stored as a global variable in the default.master.cs file:
string displayName = "Guest";
public string dName()
{
return displayName;
}
And can be looked up from any content page using:
//Make sure the user has an account
string dName = ((_default)Master).dName();
if (dName == "Guest")
{
LiteralStoreHeader.Text = "<center><b>We're Sorry!</b><br/>You must have an Avatar account to view this page.</center>";
return;
}
However, if I really do need to pull the info from a cell in the table without storing it as a variable on the default.master.cs page, I can also do that by using the ASP Table instead of the LiteralControl and then looking up the id of the Label:
Master Code File:
Label l;
public string FOO()
{
return l.Text;
}
protected void Page_Load(object sender, EventArgs e)
{
l = new Label();
l.Text = "Bar";
}
Content Code File:
string dName = ((_default)Master).FOO();
I have a dynamic table where I add controls. When I open this page in Firefox the controls are unerneath each other and in Internet expl. they are horizontally aligned.
How can I set the style of this controls from the code behind?
tabCell.HorizontalAlign = HorizontalAlign.Center; // doesn't seem to work
ibtnTableOneNew.Command += eventHandelerTableOne;
ibtnTableOneNew.Attributes.Add("runat", "server");
ibtnTableOneNew.CommandArgument = i.ToString() + "|" + theRow["siteAlias"].ToString();
ibtnTableOneNew.ImageUrl = "~/img/bullet_toggle_plus.png";
tabCell.Controls.Add(ibtnTableOneNew);
tabCell.Controls.Add(cbChecked);
ibtnTableOneNewComment.Attributes.Add("runat", "server");
ibtnTableOneNewComment.ImageUrl = "~/img/Pencil.png";
tabCell.Controls.Add(ibtnTableOneNewComment);
tabRow.Cells.Add(tabCell);
Try setting tabCell.Wrap = false. That should do what you need.
Textbox1.text is user can enter html page name, so that its is appending to panel through literal.(loading html page to pannel).
string val = TextBox1.Text;
string location = Server.MapPath(".");
string path = location + "\\HTML\\" + val + ".html"; // HTML IS FOLDER NAME IN MY PROJECT
string readText = System.IO.File.ReadAllText(path);
Panel1.Controls.Clear();
Literal lit = new Literal();
lit.Text = readText;
Panel1.Controls.Add(lit);
Actually in Html page few controls which are in format of input (<input style="position: relative;" id="T0" onmouseup="mUp(this.id)" class="ui-draggable" onmousedown="mDown(this.id)" value="" type="text">)
I have to find those id's and text to save in database.
how to find the controls in panel now?
Give an ID to the control when you add it.
Literal lit = new Literal();
lit.Text = readText;
lit.ID = "myLiteral";
Panel1.Controls.Add(lit);
Then you can get it back as follows:
Literal lit = (Literal)Panel1.FincControl("myLiteral");
Remember that dynamically added controls must be created added again on every PostBack that follows as long as you want to have access to them.
Give your Literal an ID and then you can access it via FindControl...
Literal myLiteral = Panel1.FindControl("litId") as Literal;
if (myLiteral != null)
{
// ... do something
}
EDIT: (Missed the last part of your question)
You need to use ParseControl([string value]) on the HTML content which returns a control and then add that control (containing all child controls) to the Panel. Then you can use FindControl to locate child controls. For this method, the controls must be .NET controls (ie.
Since you did not give id to the control, u can find them by Panel1.Controls[index], since it is the first control added u can access at Panel1.Controls[0]