How to append a WebControl immediately after a WebControl in CodeBehind - c#

Now that i've been MVCing for quite sometime i decide to pop some classic C# .Net into my 8 track and have gotten the following issue:
I have a TextBox WebControl on my aspx page that in the code behind i want to simply append a LiteralControl after it.
This doesn't work:
TextBoxAge.Controls.Add(new LiteralControl("Invalid Age."));
This works but all the way at the bottom:
TextBoxAge.Controls.Parent.Add(new LiteralControl("Invalid Age."));
Can you help me!?
For example the HTML will show:
<div>
<input name="TextBoxAge" type="text" id="TextBoxAge" class="Age">
Invalid Age.
</div>
This should be purely dynamic and relative to the control at hand.
Solution:
TextBoxAge.Parent.Controls.AddAt(TextBoxAge.Parent.Controls.IndexOf(T‌​extBoxAge),new LiteralControl("<span>Invalid Age.</span>"));

Maybe you can try something like this. (Don't remember if AddAt will replace the control at the specified index )
var textBoxAgeIndex = TextBoxAge.Parent.Controls.IndexOf(TextBoxAge);
TextBoxAge.Parent.Controls.AddAt(textBoxAgeIndex +1, new LiteralControl("Invalid Age."));
Hope this will help

The best way is to use an a PlaceHolder
From MSDN: Use the PlaceHolder control as a container to store server
controls that are dynamically added to the Web page.
PlaceHolder.Controls.Add(new LiteralControl("Invalid Age."));

Related

ASP.Net Label change in C#

I am usually dealing with c# code , but recently developing a asp.net page , I have a Calendar that Appears and the user selects the date he/she wants. On that page is a asp lbl that i would like to display the currently selected date, which is normally easy for me but i am having trouble referencing/finding the control . Also I am unsure of the best way to do achieve this and i'm sure to come across this problem in the future.
This is where I would like to set the lbl text and have tried using the FindControl method but it's not working for me , thinking its possibly nested as i have some divs?.
public void Calendar1_SelectionChanged(object sender, System.EventArgs e)
{
Control Lbl = FindControl("inputField");
if (Lbl != null)
{
//Control mycontrol2 = Lbl.Parent;
Lbl.Text = Calendar1.SelectedDate.ToShortDateString();
}
and this is in asp.
<div id="date">
<input type="text" size="12" id="inputField" />
<script>
$("#inputField").click(function () {
$("#box").show("slow");
});
</script>
</div>
How do I accomplish setting the inputfield text to the Calendar.SelectedDate ?.
(and any tips you have come across yourself if any, for good practice)
Thanks For any help.
Any reason why you're not using an asp:Label? You can't find the "label" because it is an html control, aka a client side control. Use an <asp:Label id="lblCal" runat="server"... and you should have no problem changing its text in code behind:
lblCal.Text = Calendar1.SelectedDate.ToShortDateString();
Asp.Net considers only server tags as being controls available at C# level.
All those DIVs and other tags are just plain text for the Asp.Net, they will no be considered in the control hierachy.
To make Asp.Net consider it in the server, place the runat="server" attribute on the tags of your interest. They will become accessible in the code-behind by the name placed in the id attribute.
Asp.Net will never be abled to find the 'inputField' in your sample code.
Solution:
To solve your problem I recommend you use an Asp.Net WebForm control called TextBox... if what you want is an input:
<asp:TextBox runat="server" id="inputField" />
By doing this, you will be abled to access the inputField, in the code-behind by name:
inputField.Text = Calendar1.SelectedDate.ToShortDateString();

Change CSS on span tag in ASP.NET Web Forms

I am trying to change the CSS for a span tag using C# but I am unable to do so. I have tried to give it a type of HTMLGenericControl but cannot get the CssClass tag to popup in IntelliSense.
<span id="collegeSpan" runat="server" class="college">other code here</span>
Have you tried:
collegeSpan.Attributes["class"] = "foo";
Because a late answer is better then no answer at all, for the record:
If you're able to alter the HTML/ASCX; use the asp:Label-control instead of a span. Label-controls are rendered to the page as a span, but it has some advantages, including the possibility to alter the "CssClass"-property :-)

ASP.NET Create textbox on fly using javascript

I want to create a textbox on the fly (in the comment section im creating). Now I would like your opinion on whats the best solution. I was thinking about using a webmethod and add a textbox control dynamically, but since this requires a call to the server I'm not sure if that's the best option. Or can i also spawn a textbox using plain old javascript and still getting it's value on postback?
Thanks again guys
Kind regards,
Mark
Put the TextBox using ordinary HTML input element on page and set its visibility property to collapsed using style tag then in code behind make it visible.
HTML Tag:
<input id="myTextBox" type="text" style="visibility: collapse;" />
Javascript:
var txt = document.getElementById("myTextBox");
txt.style.visibility = "visible";
Hope this helps!
You can create a new element using plain old JavaScript:
var textbox = document.createElement("textarea");
textbox.className = "my-textarea"; //Styling with CSS
document.getElementById("myelement").appendChild(textbox);

Dynamically create controls using stringbuilder

i have been trying to create controls dynamically on my web page using the StringBuilder class..and i dont quite seem to get through...
any help would be appreciated.
i am trying to do this...
StringBuilder sbTest = new StringBuilder(string.Empty);
sbTest.Append("<input type=\"text\" id=\"txt1\" runat=\"server\" />");
Response.Write(sbTest.ToString());
The page for sure displays a TextBox on the browser which is easily accessible through JavaScript...but what i want is the control to be available on the Server Side too...so that when the page is posted back to the server i can easliy obtain the value that has been entered by the user into the textbox.
Can any 1 please help me with this....
thank you so much....
Like Torbjörn Hansson says, if you just add a name attribute (and maybe remove runat="server" from your original snippet) you'll be able to access the submitted value but you'll only have a client-side HTML <input /> element.
If you are wanting to dynamically create server-side controls then you'll have to do something like this:
TextBox textbox = new TextBox {
/* take care to create unique ID's if you're adding more than 1 TextBox */
ID = "foo",
Text = "bar"
};
Controls.Add(textbox);
In an answer almost about the something I answered this
You should do the things properly and not trying to reinvent the wheel.
Creating controls Dynamically you can choose 2 ways, the .NET way, or the Javascript way
Both are seen by any of the other, in other words, creating controls using the .NET way, javascript can see and use it and vice versa.
.NET way
in your HTML file add something like
<body>
<form id="form" runat="server">
<asp:PlaceHolder id="ph" runat="server" />
</form>
</body>
in your script part
TextBox txt = new TextBox();
txt.ID = "myTxt";
ph.Controls.Add(txt);
you can easily get that TextBox in javascript using:
var myTxtValue = $("#myText").value();
Javascript Way
var txt = $("<input />", {
id : "myTxt"
});
txt.AppendTo("body");
in .NET you get the value using
string value = Request["myTxt"];
NOTE All javascript lines uses jQuery for simplify results
Provide a name-attribute and access it with:
Request.Form["txt1"]
You can get the value from
Request["txt1"]

How to set value of <input type="hidden"> in asp .net page_load without using runat="server"

i need to do the following two things...
i want to set value of in asp .net page_load. the problem is that i dont want to use runat="server". i have tried this the following but it does not work:
HtmlInputHidden hiddenControl = (HtmlInputHidden) FindControl("a");
is there a way to access in asp .net page_load without using runat="server"? ? ?
i can do this if i use but in this case i cannot access it in master page's javascript function. i have tried this but it does not work...
var hdnField = document.getElementById('<%= hdnIdentity.ClientId%>');
var hdnField = document.getElementById("hdnIdentity").getAttribute("value");
var hdnField = document.getElementById("hdnIdentity").value
what i need... i want to access content page's hidden field value in javascript in master page. is there a way ? ? ? thnx in advance regards Haroon haroon426#yahoo.com
I sometimes do the following, especially when I want control over my ids (especially when using jquery).
<asp:literal id="literal1" runat="server"><input type="hidden" id="someid" value="{0}"/></asp:literal>
Then, in codebehind you can set the value with the following:
literal1.Text = string.Format(literal1.Text, "somevalue");
This doesn't really get around using runat="server", but you haven't specified why you don't want to do that. Also, you'd have to get the value with a request.form
Update
In .net 4.0 you have much more control over your IDs. See this for more information:
http://weblogs.asp.net/asptest/archive/2009/01/06/asp-net-4-0-clientid-overview.aspx
IIRC, you need to look in the HttpRequest.Forms, somewhere in there.
If the value is part of a POST form then you want to check Request.Forms or Request.QueryString if it's a GET form.
ad 1) in aspx file just write <input type="hidden" value="<%=GetHiddenValue%>" />. And in your code behind define protected property
public class MyPage : Page {
protected GetHiddenValue { get { /*...*/ } }
You can use it in your master page javascript how ever the control name is not what you expect it to be you'd need to use ClientID to get that. If you do not apply runat=server you can only get a hold of the control as text by either traversing the .aspx file or as some one mentioned embedding it in a named tag and then doing string manipulation on the inner HTML. That is for setting it. If you need to get the value use Request[tagName] or similar
ad 2) You can use simple html code in your content page with specified id <input type="hidden" id="myHiddenField" />. Then in master page javascript use document.getElementById('myHiddenField').

Categories

Resources