hi guys i am using this code in my aspx page
<%for (int i=o;i<5;i++)
{%>
<asp: link button id=i text=i/>
<%}%>
at it's producing five link buttons like
i i i i i
but i just want five link buttons like that
1 2 3 4 5
with id=1,2,3,4,5 respectively
how can I can implement that
Put a placeholder in the page where you want the links:
<asp:PlaceHolder ID="LinkContainer" runat="server" />
In the Page_Load method in code behind, you put the links in the placeholder:
for (int i = 1; i <= 5; i++) {
LinkButton link = new LinkButton();
link.ID = "Link" + i.ToString();
link.Text = i.ToString();
LinkContainer.Controls.Add(link);
}
This way the controls will be created early in the page cycle, and it's possible to hook up server side events to them if you like.
(Note that I added a prefix to the id. Having an id that is only digits can cause problems in some situations.)
This isn't exactly the best way to do things in ASP.Net. Dynamic controls have many gotchas, and you just found one of them. This code is a little better (make sure the page calls DataBind() at some point):
<%for (int i=0;i<5;i++)
{%>
<asp:LinkButton id="<%# i%>" runat="server" text="<%#i%>" />
<%}%>
but you'll find that events and changes don't wire up the way you'd expect them to, if it works at all. With only five of them, it's better to just list them out by hand, and things will be much easier down the road. Or, if they came from a datasource somewhere use a repeater and create them that way.
Really, you don't want to mix code into your aspx markup at all if you can help it. Leave it for the code behind!
You need to be careful how you actually render this. Note that HTML ids that start with a number are illegal according to the specification. I would prepend some alphabetic character to the id value to be sure that it is both legal HTML and that the control id generated is legal for ASP.NET. It's unclear to me whether it's legal or not to use just a numeric value for a control id. Note that ASP.NET control id characters must be alphanumeric or an underscore.
HTML Reference:
ID and NAME tokens must begin with a
letter ([A-Za-z]) and may be followed
by any number of letters, digits
([0-9]), hyphens ("-"), underscores
("_"), colons (":"), and periods
(".").
ASP.NET Reference
Note: Only combinations of
alphanumeric characters and the
underscore character ( _ ) are valid
values for this property. Including
spaces or other invalid characters
will cause an ASP.NET page parser
error.
YOu need to actually print out the value of I on the server side.
<%for (int i=o;i<5;i++) {%>
<ASP:LinkButton Id="<%# i%>" Text="<%# i %>" />
<%}%>
Related
For making an existing site to multilingual, I follow globalization technique, I have created 3 resource files for different content like label & header text file, grid header text file etc...
Now I have two keys in different resource files i.e Email and Message, at a third place I want to show both these keyword together i.e Email message. Do I need to create third key or I can concatenate already existing keys. Currently I am using below two codes
For showing directly on page:
HttpContext.GetGlobalResourceObject("ResourceLabelButton", "Email")
For showing as text of any control like Textbox, label:
Text ="<%$ Resources:ResourceContent, Email %>"
I can concatenate two resource string on .cs page but it will increase timeline, so please suggest so I can only change on .aspx pages.
Thanks in advance
ASP.NET tag attribute values that use <%$ Something: Something Else %> are of a special syntax called ASP.NET Expressions. Using them as attribute values are pretty much all-or-nothing; there's no way to add any code into the ASPX file to manipulate what those expressions evaluate to. You'll have to do this in the code-behind.
You should create a separate resource entry for "Email Message" instead of concatenating "Email" and "Message". To understand why, look at Spanish:
Email = Correo electrónico
Message = Mensaje
Simple concatenation gives you Correo electrónico Mensaje. This is wrong. The correct translation is:
Email Message = Mensaje de correo electrónico
Notice that in the translation, the order of "Email" and "Message" has been reversed, and a new word (de, which means "of") has been inserted between them.
On the other hand, look at the translations for "New Message" and "Last Message":
New Message = Mensaje nuevo
Last Message = Último mensaje
As you can see, there are complex rules that govern when to reverse the order of words and when to insert de. These rules, of course, are different in other languages.
So in general, you should never concatenate localized words or phrases to form a longer phrase.
Always provide a separate resource entry for every phrase.
I was having the same issue, and I solved it by using this option instead:
<asp:Label id="lbl1" runat="server" Text="Email: <%= HttpContext.GetGlobalResourceObject("ResourceContent", "Email") %>">
For local Resources, use the GetLocalResourceObject method instead of GetGlobalResourceObject
If this value is being used very often make a third key for the same, else concatenate at runtime
Try with the below code
<asp:Label ID="lblNameAndNos" runat="server">
<%= ""+ Resources.Resources.Name + "/" + Resources.Resources.Nos %>
</asp:Label>
Instead of using inside Text property use the above way
I've trawled the net looking for the syntax to get this working and i'm hoping this is a quick fix else i'll go mad. Basically I have a nested repeater and the button below hides another nested repeater.
((location_details)((RepeaterItem)Container.Parent.Parent).DataItem).tbl_location.location_id evaluates perfectly well (3824 in the case i'm testing), but when I try to pass it so that its a string parameter for the javascript function it fails everytime.
<asp:Linkbutton ID="lb_showhide_oloc_gnotes" runat="server" Text="Expand/Close"
href='javascript:sltoggle('" + <%# ((location_details)((RepeaterItem)Container.Parent.Parent).DataItem).tbl_location.location_id %> +" '); return false;' />
Any ideas what i'm missing (I know the above syntax is wrong I must have changed it 100 times already but you get the idea).
thanks!
Have you tried asp:HyperLink and NavigateUrl?
I think asp:LinkButton renders to an anchor tag and its href attribute should be generated by ASP (so it results in a postback) and that's why it won't bind to it.
I can't test this right now so this might be wrong, but you don't need to concatenate the value of href together.
<asp:Linkbutton ID="lb_showhide_oloc_gnotes" runat="server" Text="Expand/Close"
href='javascript:sltoggle("<%# ((location_details)((RepeaterItem)Container.Parent.Parent).DataItem).tbl_location.location_id %>"); return false;' />
This is my javascript
function btnEditClick() {
alert(document.getElementById('<%=LblRefPhyID.ClientID %>').value);
}
<asp:Repeater ID="repeaterRefPhysicianList" runat="server">
<ItemTemplate>
<tr onclick="selectRow(this);">
<td class="csstablelisttd" style="display: none;">
<asp:Label ID="LblRefPhyID" runat="server" Text='<%#Eval("Ref_Phy_ID")%>'></asp:Label>
</td>
on clientclick of Edit button i have to pass RefphyId to another page how can i do that..
It's a repeater. That means that the ItemTemplate will be repeated for each item in your databound collection.
This comes with a caveat: IDs are supposed to be unique. So when you say that your asp:Label has an ID of LblRefPhyID, ASP.NET automagically does you the favor of generating unique IDs for each instance of the repeater that eventually makes its way to your generated HTML. These generated IDs will be based on your original value of LblRefPhyID, but it won't be exactly that, so a plain document.getElementById() outside of the repeater won't work.
There are many ways to work around this, and the very first step you need to do is to actually write some code that will take the automatic generated IDs into account. Maybe write some Javascript to cache the IDs using LblRefPhyID.ClientID, maybe do it dynamically onclick, whatever.
EDIT
And, oh yeah, #Pointy is completely correct in stating that label elements don't have values, just their inner HTMLs. I don't get why he got downvoted for giving a correct response.
Try to set css class instead of id and bind elements click event by class name.
I'm using jquery for this:
$(document).ready(function(){
//bind click event on our label class
$('.lblRef').live('click', function(){
alert($(this).text());
});
});
And this in asp.net page code:
<asp:Label CssClass="lblRef" runat="server" Text='<%#Eval("Ref_Phy_ID")%>'></asp:Label>
HTML <label> elements don't have a "value". They do have contents:
alert(document.getElementById('<%=LblRefPhyID.ClientID %>').innerHTML);
Best way would be to check what is the pattern of id generated by the repeater on the client side and then you can use that id to get the value of the label using innerHTML.
For instance in your case id generated may be :
repeaterRefPhysicianList_LblRefPhyID_01 to till the number of rows in source.
So you can use this information with innerHTML to get the value of the label..
All in all just check your html page you will know what to do next :)
What are the appropriate use of these two controls? From time to time I build up HTML in the code behind. Sometimes I want to output white space and I end up doing something like this.
const string twoSpaces = " ";
p.Controls.Add(new Literal { Text = twoSpaces });
or
const string twoSpaces = " ";
p.Controls.Add(new LiteralControl { Text = twoSpaces });
My question is, is this an appropriate use of these controls? Should I be adding whitespace this way? When do I use one over the other?
I realize I could probably do something with CSS, but I really want to know what are the purposes of these two controls, and is there anything inherently wrong with using them in this fashion.
Literal uses ViewState and will remember any updates to its properties across Postbacks. LiteralControl must have its properties set on every postback.
Other than that, be very careful when using Literal. If you allow user input to be rendered in a Literal tag, you have very likely opened up a XSS attack.
Chris Pitman has answered it correctly, but I just want to add some more facts about both.
Literal is a control which can be added on both an aspx page as well as to the code behind.
asp:Literal Text="text" runat="server"
But LiteralControl cannot be added on aspx page, but only to the code behind. So that is why LiteralControl doesn't have its ViewState associated to the page class.
In a custom server control, I am simply writing out the number of child controls.
Is there a reason that the count would go to zero if <% %> tags are used within the body of the control tags?
Here's my extremely simplified control:
public class Script : Control
{
public override void RenderControl(HtmlTextWriter writer)
{
writer.Write(this.Controls.Count.ToString());
}
}
When passed only Literal data, the count written is 1 as expected:
<my:Script runat="server" ID="script3" >
function foo(){}
</my:Script>
When passed Literal data and some computed data, the count goes to zero:
<my:Script ID="Script1" runat="server" >
function foot(){}
<%=String.Empty %>
</my:Script>
There's nothing special about the String.Empty either. Anything I put here results in a count of zero.
Interestingly enough, other Control tags work fine however. The following counts 3:
<my:Script runat="server" ID="Script2">
hi
<asp:HyperLink runat="server" NavigateUrl="/" Text="hi" />
</my:Script>
Is there another way to get the child "content" of the custom control? I would think there is some way, as does it, but I can only inspect the metadata for System.Web.UI.WebControls.Content - not the implementation.
It's not possible to modify the Controls collection if your control has <%%> tags in the body (if you try to Add something, then you get an exception explaining just that). And for the same reason, the Controls collection is in fact empty. You can check if the collections is empty because of <%%> tags using the Controls.IsReadOnly property.
Turns out the answer was much more simple than the approach I was taking in the first place. Simply call the overridden RenderControl method with your own HtmlTextWriter and then use the captured markup however you want.
var htmlString = new StringBuilder();
var mywriter = new HtmlTextWriter(new StringWriter(htmlString));
base.RenderControl(mywriter);
Now the rendered markup is available in htmlString, regardless of <% %> tags used in the control's body.