Find div at run time at server side in c# - c#

Hye all.
i have div in index.aspx page like this
<div id="MainDiv" runat="server">
and i am creating div from server side(At run time) like
for (Int32 i = 0; i < 4; i++)
{
//Create here divFinal
HtmlGenericControl divFinal = new HtmlGenericControl("div");
divFinal.ID = i.ToString();
divFinal.Attributes.Add("class", "column");
mainDiv.Controls.Add(divFinal);
//add to maindiv
HtmlGenericControl div = new HtmlGenericControl("div");
div.ID = "t_e_" + i.ToString() + "_a";
div.Style["background-color"] = "#CFD8E6";
div.Attributes.Add("class", "grid");
div.Attributes.Add("onclick", "OnMouseDownDiv(this)");
div.Attributes.Add("onmouseover", "OnMouseDown(this)");
div.Attributes.Add("onmouseout", "OnMouseUp(this)");
divFinal.Controls.Add(div);
// add to dvfinal
}
After gen rate its look like this in HTML form
<div id="mainDiv"><div id="0" class="column"><div id="t_e_0_a"></div></div><div id="1" class="column"><div id="t_e_1_a"></div></div></div>
Now I need to find div id t_e_0_a inside main Divdiv.
HtmlGenericControl div =
((HtmlGenericControl)showdiv.FindControl("0"));
But its give me error....

You can't do it like you want as it is not a control. You should place runat="server" attribute on it, or you can get it somehow from showdiv.InnerHtml - there it should be presented as a string which you can parse with some HTML parser for .net (for instance, HTMLAgilityPack suggested here)
To create server side controls at run time, you can use something like below:
for (Int32 i = 0; i < 2; i++)
{
HtmlGenericControl div = new HtmlGenericControl("div");
div.ID = i.ToString();
div.InnerHtml = i.ToString();
div.ClientIDMode = ClientIDMode.Static; //this is for .NET 4.5 only. Required to have ClientID the same as ID.
showdiv.Controls.Add(div);
}
and than, after controls are added, you should be able to use something like this:
HtmlGenericControl div=((HtmlGenericControl)showdiv.FindControl("1"))
to get those controls. But please remember that controls added like that, must be added for each request.

you should have tried with recursive function that how Page.FindControl works.
private Control getFollowingControl(Control c, string key,out Control returnControl)
{
if(c.hasChild)
{
foreach(Control item in c.controls)
{
getFollowingControl(item,key,out returnControl);
}
}
else
{
if(c.Id==key)
{
returnControl=c;
break;
}
}
}
Now you can use above recusive function to find any control at any depth....
Control getThisControl=null;
getFllowingControl(this,"myButton1",out getThisControl);
At the end it would give you the control that has Id="myButton1" in GetThisControl control object.

Related

How to get the id of a div tag in code behind

I am having two div tags and in it there are linkbuttons. When I click on any of the linkbutton I need to get the id of div tag in code behind. I have no idea how to do this.
Below is my code of one div tag:
<div id='qhse' class="qhse" runat="server"></div>
And C# code:
public void GetQHSEManual()
{
DataTable dsMenu = new DataTable();
gObj.category = "1";
dsMenu = gObj.GetAllSubCategory();
for (int i = 0; i < dsMenu.Rows.Count; i++)
{
LinkButton myLnkBtn = new LinkButton();
myLnkBtn.ID = "lbtn1" + dsMenu.Rows[i]["Subcategory"].ToString();
myLnkBtn.CssClass = "linkButton";
myLnkBtn.Click += new EventHandler(Dynamic_Click);
myLnkBtn.Text = dsMenu.Rows[i]["Subcategory"].ToString();
myLnkBtn.Text += "<br>";
qhse.Controls.Add(myLnkBtn);
}
}
$("a:contains('continue')").closest('div').attr('id');
Here in this code we are finding parent div id of a href having a text value in display as 'continue'.
You should do it with JavaScript. If you have 1 element inside of your div holder this should be done easy. JavaScript lib allows to use parent id when you click on your button inside div. See jQuery for this purpose.
I would suggest you that you separate server side and client side logic well. Think about local storage, sessions and cookies if you need to pass some data to the backend. In your case I would use an AJAX call from the client and implement some logic on the backend.

Creating and finding dynamic controls on a page

There is a problem to find a dynamic control on a page. The dynamic control is created every time when a user press a button. The button calls the following JavaScript function and create a new components.
<script type="text/javascript">
var uploadCount = 1;
function addFileInput(fName) {
var only_file_name = fName.replace(/^.*[\\\/]/, '');
var $div = $('<div />', {runat: 'server'});
var $cbox = $('<input />', { type: 'checkbox', id: 'attachement' + uploadCount, value: fName, checked: "true", runat: 'server'}).addClass;
var $label = $('<label />', { 'for': 'attachement' + uploadCount, text: only_file_name });
$div.append($cbox);
$div.append($label);
$('#newAttachment').append($div);
$("#uploadCountValue").prop("value", uploadCount);
uploadCount++;
}
</script>
newAttachment is DIV section on the page.
<div id="newAttachement" runat="server" />
The DIV section is situated inside section. The problem is when a user presses the button on the form I can't find the dynamic created components. The following code shows how I try to find the components:
for (int i = 1; i <= Convert.ToInt32(uploadCountValue.Value); i++)
{
if (RecursiveFind(newAttachement, "attachement" + i) != null)
{
... to do something
}
}
public Control RecursiveFind(Control ParentCntl, string NameToSearch)
{
if (ParentCntl.ID == NameToSearch)
return ParentCntl;
foreach (Control ChildCntl in ParentCntl.Controls)
{
Control ResultCntl = RecursiveFind(ChildCntl, NameToSearch);
if (ResultCntl != null)
return ResultCntl;
}
return null;
}
I have detected that Controls count value is always zero in spite of there are dynamic components there.
I would be happy to get any help from us. Thanks.
to find the controls created in the client-end you can't search them in the Page.Controls collection instead try to look for them in the Request.Form[] array
you are creating the dynamic controls in javascript? i.e. you are creating html elements in javascript. It won't matter even if you put a runat="server" attribute in there, because it is still at the client-end. That would not be a part of the viewstate bag, so not populated in the controls collection.
you need to change your logic. create dynamic control in code-behind on button postback.

How to use a Variable or Function to declare my SqlDataSource ID in HTML

I'm writing a for loop that displays a list of links with some chartfx display. The chartfx needs an sqlDataSource. I'm trying to give the unique ID each time the for loop does one iteration but I can not pass it a value or function. Example below in my code.
getSQLID() is just a function that returns a string which I want to be my ID. This is all done on the aspx page and the function is in the .cs . Any help would be really appreciated thank you.
//name of the contentplace holder on the aspx page
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server" >
//code behind
Control ctrl = LoadControl("WebUserControl.ascx");
Control placeHolderControl = this.FindControl("Content2");
Control placeHolderControl2 = this.FindControl("ContentPlaceHolder1");
ctrl.ID = "something";
if (placeHolderControl != null)
placeHolderControl.Controls.Add(ctrl);
if (placeHolderControl2 != null)
placeHolderControl2.Controls.Add(ctrl);
First of all, recall that server controls declared in the designer like this are attached to your class at compile time. So it doesn't make sense to try to create multiple instances in a loop at runtime, and that's why the values in e.g. the Id tag have to be known at compile time.
One alternative is to create them in the code behind, with something like:
for (int i=0; i<2; ++i)
{
var chart = new Chart();
chart.Id = "chartId" + i;
chart.DataSourceId = "srcid" + i;
var src = new SqlDataSource();
src.Id = "srcid" + i;
Controls.Add(chart); // either add to the collection or add as a child of a placeholder
Controls.Add(src);
}
In your case converting all of those declarative properties to the code behind can be a bit of work (though it is possible). An alternative is to make a user control (ascx) that contains the markup that's now in your aspx page. You would instantiate the controls in your code behind with something like:
for (int i=0; i<2; ++i)
{
var ctrl = LoadControl("~/path/to/Control.ascx");
ctrl.Id = "something_" + i;
Controls.Add(ctrl); // again, either here or as a child of another control
// make the src, hook them up
}

how do you create an <h1> tag programmatically in ASP.NET?

I'm trying to generate some html programmatically in my code behind for a user control I'm designing.
I've been looking around, but can't seem to figure out how to dynamically generate some h1 tags for content I'll be displaying.
Is it just a Label with a special property set?
var h1 = new HtmlGenericControl("h1");
h1.InnerHtml = "header content";
You could also use:
<h1 runat="server" />
You can use label or literal controls as shown below:
Label1.Text = "<h1>HI All</h1>";
Or
string heading = "HI All";
Label1.Text = string.Format("<h1>{0}</h1>", heading);
You can do this easily by
literall.Text ="<h1>ABCD</h1>";
Let, you have a server control like this,
<div class="cls" runat="server" id="MyServerControlDiv"></div>
using HtmlGenericControl
var h1 = new HtmlGenericControl("h1");
h1.InnerHtml = "header content";
MyServerControlDiv.Controls.Add(h1);
using LiteralControl
MyServerControlDiv.Controls.Add(new LiteralControl("<h1>"));
MyServerControlDiv.Controls.Add(new LiteralControl("header content"));
MyServerControlDiv.Controls.Add(new LiteralControl("</h1>"));
Use Literal control, Literal1.Text = "<h1>" + texttodisplay + "</h1>";
ASP literals may help you.
http://ganeshmohan.wordpress.com/aspnet-and-c-generate-html-controls-dynamically/
Personally I prefer to make a class for it.
public class H1: HtmlGenericElement
{
public H1(): base("h1") { }
}
Or maybe.
public class H: HtmlGenericControl
{
public H(int size): base("h" + size) { }
}
Let us assume that you have an asp placeholder in your design:
PlaceHolder placeHolder1 = new PlaceHolder();
string yourText = "Header Text";
Label myLabel = new Label();
myLabel.Text = "<h1>" + yourText + "</h1>";
PlaceHolder1.Controls.Add(myLabel);
OR
PlaceHolder1.Controls.Add(new LiteralControl ("<h1>")) // and likewise
for </h1>.
Using a generic HTML control or a literal control is fine just so long as you don't want to insert any child controls. If you do need to append a child control such as a label for example, then you will want to create you header as a Web Control like follows:
WebControl H2Header = new WebControl(HtmlTextWriterTag.H1);
And then you can append a child control like this:
Label labHeader = new Label() { Text = "Some Header Text" };
H2Header.Controls.Add(labHeader);
What i always prefer to use:
In the front end put the desired html control like
<h1 id="title" runat="server">XXX</h1>
Then in the behind code declare the desired control like
protected HtmlGenericControl PublicTitle
{
get
{
return this.title;
}
}
And anywhere in the code play whith the control
PublicTitle.InnerHtml = state.Equals("win") ? "Win" : "Lost";
PublicTitle.Attributes.Add("src", "https://xxxx");

Accessing multiple values from generated panel

I have some logic that loops and adds a new Panel control to another control:
for (int segmentIndex = 0; segmentIndex < segments.Length; ++segmentIndex)
{
holder.Controls.Add(new Panel() { Width = Unit.Percentage(segments[segmentIndex] / segmentsSum * 100), CssClass = String.Format("segment segment-{0}", segmentIndex) });
}
container.Controls.Add(holder);
This works great, but there are a few values that I need to store on each panel within the loop. I need to be able to access these values in both c# and javascript, once the control is rendered on the page. What would be the best way to achieve this? I've used the Tag property before on some controls, but a Panel doesn't have one.
Thanks so much
It sounds like you need to add markup inside of the Panel, is that correct? If so, you can add a control to the Panel control's Controls collection, such as a Label or a LiteralControl.
The following (non-tested) code illustrates this point:
for (int segmentIndex = 0; segmentIndex < segments.Length; ++segmentIndex)
{
var p = new Panel() { ... };
var innerContent = new LiteralControl("<p>Hello, World!</p>");
p.Controls.Add(innerContent);
holder.Controls.Add(p);
}
container.Controls.Add(holder);
Alternatively, instead of a LiteralControl you could add a Label, a Button... whatever you need.
Add a HiddenField to your panel. It will render in HTML as <input type="hidden" /> so it's invisible, accessible for your server code and also for your javascript.
LiteralControl innerContent = new LiteralControl("<p>Hello, World!</p>");
HiddenField hiddenContent = new HiddenField() { ID = "hiddenContent", Value = "My hidden content" };
p.Controls.Add(innerContent);
p.Controls.Add(hiddenContent);

Categories