So basicly im adding elements to my html, via litterals from the backend.
It works great when using it in the asp content placeholders. But i need it to be another specific place on a specific page. Ive tryed making div's with runat="server" But it does not seem to work.. Does anyone have any experience with what i could use? This is part of my code:
foreach (var something in somethingelse)
{
this.Page.Form.FindControl("ContentPlaceholder1")
.Controls.Add(
new LiteralControl("It's a long list, so just typing this.")
);
}
You can use runat="server" on divs. For example:
<div id="myNewDiv" runat="server"></div>
and in the code behind:
myNewDiv.InnerHtml = "Some new text in the div";
If you need to create the divs dynamically you can do the following:
for (var i = 0; i < 10; i++)
{
var ele = new HtmlGenericControl("div")
{
InnerHtml = string.Format("new div {0}", i),
ID = string.Format("NewDiv_{0}", i)
};
Page.Form.FindControl("MainContent").Controls.Add(ele);
}
You can even push the new divs into an existing div which is anywhere in the ContentPlaceHolder:
var page = Page.Form.FindControl("MainContent").FindControl("myNewDiv").Controls;
for (var i = 0; i < 10; i++)
{
var ele = new HtmlGenericControl("div")
{
InnerHtml = string.Format("new div {0}", i),
ID = string.Format("NewDiv_{0}", i)
};
page.Add(ele);
}
Place a HTML tag in source as below
<table>
<tbody>
<-- Your literal control here -->
</tbody>
</table>
and in code behind set literal1.Text ="<tr><td>'"+ Your data here +"'</td></tr>" and it will work
Related
I'm using ASP.NET C# to display a catalog of items. When the user selects an item, I display the details of that item and I'd like to display one or more pictures. I tried a few methods for this and settled on the Blueimp carousel. It's working just fine if I populate the links div in the html, but I need to show different pics (from URLs in the SQL Server DB) depending on the item.
The code below works to populate the links div, but all I see is a blank space on the screen--no carousel, no images.
<div id="IllustrationDiv" runat="server">
<!-- Links div goes here -->
<script>
document.getElementById('links').onclick = function (event) {
event = event || window.event
var target = event.target || event.srcElement
var link = target.src ? target.parentNode : target
var options = { index: link, event: event }
var links = this.getElementsByTagName('a')
blueimp.Gallery(links, options)
}
</script>
<!-- The Gallery as inline carousel, can be positioned anywhere on the page -->
<div id="blueimp-gallery-carousel"
class="blueimp-gallery blueimp-gallery-carousel"
aria-label="image carousel">
<div class="slides" aria-live="off"></div>
<h3 class="title"></h3>
<a class="prev"
aria-controls="blueimp-gallery-carousel"
aria-label="previous slide"></a>
<a class="next"
aria-controls="blueimp-gallery-carousel"
aria-label="next slide"></a>
<a class="play-pause"
aria-controls="blueimp-gallery-carousel"
aria-label="play slideshow"
aria-pressed="false"
role="button"></a>
<ol class="indicator"></ol>
</div>
<script src="../Scripts/blueimp-gallery.min.js"></script>
<script>
blueimp.Gallery(document.getElementById('links').getElementsByTagName('a'), {
container: '#blueimp-gallery-carousel',
carousel: true
})
</script>
</div>
ViewState["illustration_details_dt"] = dt;
// Open div
System.Web.UI.HtmlControls.HtmlGenericControl newDiv = new System.Web.UI.HtmlControls.HtmlGenericControl("DIV");
newDiv.ID = "links"; //<---Give and ID to the div, very important!
newDiv.Attributes.Add("hidden", "hidden");
for (int i = 0; i < dt.Rows.Count; i++)
{
Image newImage = new Image();
HyperLink newHyperLink = new HyperLink();
newHyperLink.NavigateUrl = dt.Rows[i]["universal_resource_locator"].ToString();
newHyperLink.Target = "_blank";
newHyperLink.Text = dt.Rows[i]["document_id"].ToString();
newImage.ImageUrl = dt.Rows[i]["universal_resource_locator"].ToString();
newImage.AlternateText = dt.Rows[i]["document_id"].ToString();
newImage.BackColor = System.Drawing.Color.White;
newHyperLink.Controls.Add(newImage); // TODO - Commented for troubleshooting
newDiv.Controls.Add(newHyperLink); // TODO - Commented for troubleshooting
}
IllustrationDiv.Controls.AddAt(0,newDiv); // Add the new div to our already existing div
I'm looking for options. If populating the links div from codebehind isn't going to work, what would work? If populating the links div from codebehind does work, what am I doing wrong?
Thanks.
I found the answer. I'm using a master page on my site with a content placeholder for the subpages. Because I'm using a ContentPlaceholderID = "MainContent", MainContent_ is appended to each of the IDs on my page, so my blueimp script looking for document.getElementById('links') needed to have "MainContent_" prepended to "links". I change the script to:
<script>
document.getElementById('MainContent_links').onclick = function (event) {
event = event || window.event
var target = event.target || event.srcElement
var link = target.src ? target.parentNode : target
var options = { index: link, event: event }
var links = this.getElementsByTagName('a')
blueimp.Gallery(links, options)
}
var carouselOptions = {
startSlideshow: true
}
</script>
The links were populating just fine, but blueimp couldn't find them. This fixed it.
I have an update panel, which fires every third seconds. I have this code into my asp.net page
<div ID="campaignDiv" runat="server" >
<ul>
</ul>
</div>
and I add its content dynamically like this:
private string CreateLiCheckbox(string checkBoxText)
{
return string.Format("<li><span class=\"textDropdown\">{0}</span><input id=\"{1}\" value=\"{0}\" type=\"checkbox\"><label for=\"{1}\"></label></li>", checkBoxText, checkBoxText + "dropdownID");
}
if (!IsPostBack) {
List<string> comps = getCompainNames();
string html = "<ul>";
for (int i = 0; i < comps.Count(); i++) {
html = html + CreateLiCheckbox(comps[i]);
}
html = html + "</ul>";
campaignDiv.InnerHtml = html;
}
My problem
when the page loads, the checkboxes are like this:
Then, I change the values to these:
but when the update pannel works, the page returns to its default statues, where nothing of the checkboxes are selected
could you help please?
I am trying to add Checkboxes dynamically to webpage
string[] words = masg.Split('~');
int size = words.Length;
CheckBox[] cbl = new CheckBox[size];
for (int i = 0; i < words.Length; i++)
{
cbl[i] = new CheckBox();
cbl[i].Text = words[i].ToString();
this.Controls.Add(cbl[i]);
// Response.Write("\n" + words[i]);
}
I am getting error
Control 'ctl01' of type 'CheckBox' must be placed inside a form tag with runat=server.
How should I proceed ? What changes to make on aspx page ? Please help.
You should change it to add in form, because this is referencing your Page. and any server control which you are creating programmatic or by adding on page with runat="server" should place inside a form tag.
like
this.Form.Controls.Add(cbl[i]);
or place a placeholder or panel on the form. and than you can add in it
like
placeholder1.Controls.Add(cbl[i]);
If your .aspx does not contain a form tag, then you should place a form tag there
like
<form runat="server" id="form1">
//Other mark up or server controls.
</form>
hi you need to add a parent control like Panel on your form and then add your check box controls to that panel
string[] words = masg.Split('~');
int size = words.Length;
CheckBox[] cbl = new CheckBox[size];
for (int i = 0; i < words.Length; i++)
{
cbl[i] = new CheckBox();
cbl[i].Text = words[i].ToString();
pnlControls.Controls.Add(cbl[i]);
// Response.Write("\n" + words[i]);
}
Add the a panle control in your aspx page :
<asp:Panel ID="pnlControls" runat="server" >
I get that error when trying to generate a number of buttons programmatically. I have no ctl02.. Why do i get that mistake?
Button pgs = new Button();//Create New Topic
pgs.Width = 20;
pgs.Command += obtainTopicsPerPage_Click;
pgs.CommandName = tPage.ToString();
pgs.Text = tPage.ToString();
btns.Add(tPage.ToString());
buttons.Add(pgs);
I create a few buttons and loop through the list (buttons). Then i get that mistake :(. ... why?
Full design:
int maximumTopicPages;
int tPage;
int questionNumber=1;
Dictionary<string, List<DisplayAllQuestionsTable>> tPages;
List<Button> buttons = new List<Button>();
protected void Answer_Click(object sender, EventArgs e)
{
ViewState["SeekPressed"] = "pressed";
tPages = new Dictionary<string, List<DisplayAllQuestionsTable>>();
string subTopic = SubTopicDropDownList.SelectedItem.Value;
List<DisplayAllQuestionsTable> threadsByTopic = new List<DisplayAllQuestionsTable>();
List<string> btns = new List<string>();
foreach (var topicKeys in postsByTopic)
{
if (topicKeys.Key == subTopic)
{
foreach (var item in postsByTopic[topicKeys.Key])
{
questionNumber++;
maximumTopicPages++;
threadsByTopic.Add(item);//Adds All DisplayAllTables objects
//if there are 20 add a button.
if (maximumTopicPages == 20)
{
tPages.Add(tPage++.ToString(), threadsByTopic);//Add a number to the page each time, with a DisplayTable object
//new Button
Button pgs = new Button();//Create New Topic
pgs.Width = 20;
pgs.Command += obtainTopicsPerPage_Click;
pgs.CommandName = tPage.ToString();
pgs.Text = tPage.ToString();
btns.Add(tPage.ToString());
buttons.Add(pgs);
maximumTopicPages = 0;
threadsByTopic.Clear();
}
}//number of questions per page
if (!tPages.ContainsKey((questionNumber / 20).ToString()))
{
tPages.Add((questionNumber / 20).ToString(), threadsByTopic);//If A button is missing add it.
}
}
Way the buttons are added to the table:
void MyButtonTable()
{
TableRow myTableRow = new TableRow();
HtmlForm form = new HtmlForm();
form.Attributes.Add("runat", "server");
Page.Controls.Add(form);
foreach (var item in buttons)
{
TableCell myTableCell = new TableCell();
form.Controls.Add(item);
myTableCell.Controls.Add(item);
myTableRow.Cells.Add(myTableCell);
}
Table2.Rows.Add(myTableRow);
Page.Controls.Add(Table2);
}
Are you adding your buttons to the Page afterwards?
Also, if you do not specify an ID to your buttons, they will be given one automatically in the form of ctlXXX
What is in the .aspx file? Specifically, what is the 'buttons' control? My guess is, it is a placeholder or panel or something similar. In that case, you need to add this to your .aspx file:
...
<body>
<form runat="server">
...
</form>
</body>
...
That should fix it.
ASP.NET needs to have the <form> tag managed by the server in order to use server side controls on your page. If your page already has a <form> tag on it somewhere, you can just add runat="server" to that tag and it will fix it. (That assumes the 'buttons' control that you're trying to add the dynamically created button into -- the placeholder or panel or whatever -- is itself between the <form>...</form> tags.)
Its working....
Please add your new button control into from
protected void btnsubmit_Click(object sender, EventArgs e)
{
Button objButton = new Button();
objButton.Text = "New Button";
objButton.ID = "randomButton";
form1.Controls.Add(objButton);
}
Here form1 -> form name available into .aspx file and objButton is button object.
You have to check if "buttons" (I think is a placeholder) is inside a div or a tag with runat="server"
update
If I understand you can try something like this:
HtmlForm form = new HtmlForm();
form.Attributes.Add("runat", "server");
form.Controls.Add(buttons);
Page.Controls.Add(form);
(untested)
I'm trying to modify a CSS style attribute for a div based on the information I get from a database table in the code behind of my aspx page. The following is essentially what I am trying to do, but I get errors.
Aspx:
<div id="testSpace" runat="server">
Test
</div>
Code Behind:
testSpace.Style = "display:none;"
testSpace.Style("display") = "none";
What am I doing wrong?
testSpace.Style.Add("display", "none");
It's an HtmlGenericControl so not sure what the recommended way to do this is, so you could also do:
testSpace.Attributes.Add("style", "text-align: center;");
or
testSpace.Attributes.Add("class", "centerIt");
or
testSpace.Attributes["style"] = "text-align: center;";
or
testSpace.Attributes["class"] = "centerIt";
Another way to do it:
testSpace.Style.Add("display", "none");
or
testSpace.Style["background-image"] = "url(images/foo.png)";
in vb.net you can do it this way:
testSpace.Style.Item("display") = "none"
If you're newing up an element with initializer syntax, you can do something like this:
var row = new HtmlTableRow
{
Cells =
{
new HtmlTableCell
{
InnerText = text,
Attributes = { ["style"] = "min-width: 35px;" }
},
}
};
Or if using the CssStyleCollection specifically:
var row = new HtmlTableRow
{
Cells =
{
new HtmlTableCell
{
InnerText = text,
Style = { ["min-width"] = "35px" }
},
}
};