This may be a very dumb question but I can't seem to get it working. I use at many places the following syntax for dynamically binding a property of a control in aspx file to the resource entry, e.g.
<SomeFunnyControl Text="<%$ Resources : ResClass, ResEntry %>" />
I want to do a similar thing with a class containing some constants, something like
<SomeFunnyControl Text="<%= MyConstantsClass.MyStringConstant %>" />
But this doesn't seem to work, it simply sets the text to the exact expression without evaluating it. I am using ASP.NET 3.5 btw.
I have tried the databinding approach but I get an HttpParseException saying
Databinding expressions are only
supported on objects that have a
DataBinding event.
This article: The CodeExpressionBuilder might be interesting/helpful (although written for ASP.NET 2.0).
It (seems) to enable you to write ... Text="<%$ Code: DateTime.Now %>" .... That might help, no? It is quite a bit of overhead, though.
Your code should look like this:
<asp:Label ID="lblMyStringConstant" runat="server" Text='<%# MyConstantsClass.MyStringConstant %&>'></asp:Label>
You also need to call DataBinding on that control, like this:
lblMyStringConstant.DataBind();
(It is not necessary if you are calling DataBind on entire Page or parent container of this label, because it will call DataBind for all its children)
<asp:Label ID="lbl" Text="<%# SomeText %>" runat="server" />
Then call lbl.DataBind(); or databind some container of the label.
If you have it like this it should work actually:
public static class MyConstantsClass
{
public static string MyStringConstant = "Hello World!";
}
or alternatively
public class MyConstantsClass
{
public const string MyStringConstant = "Hello World!";
}
If you declare it like
<asp:Label ID="Label1" runat="server" Text="<%= MyNamespace.MyConstantsClass.MyStringConstant %>"></asp:Label>
it won't work and the output will be "<%= MyNamespace.MyConstantsClass.MyStringConstant %>".
What you could do alternatively is to write it like this:
<asp:Label ID="lblTest" runat="server"><%= MyNamespace.MyConstantsClass.MyStringConstant %></asp:Label>
This works perfectly for me, but note you have to provide the fully qualified namespace to your class in the ASPX definition. At least otherwise it didn't work for me.
Related
My code is like this
<asp:Repeater ID="rptEvaluationInfo" runat="server">
<ItemTemplate>
<asp:Label runat="server" Id="lblCampCode" Text="<%#Eval("CampCode") %>"></asp:Label>
</ItemTemplate>
Everything looks okay to me, But it generates an error in the runtime. When I remove this part
Text="<%#Eval("CampCode") %>"
error goes.
SO I assume the issue is with databind. So I tried an alternative like this
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<label><%#Eval("CampCode") %> </label>
</ItemTemplate>
And it also works good. Can any one tell me what is the issue with my first code?
Note: I don't have access to the error message due to the special
reasons on my project , that's why I have not posted it here.
And I want to use ASP controls itself on the case that's why i haven't
gone with my second solution
The problem is with quotes. Currently you have double quotes everywhere, so ASP.NET is not able to parse this. Change outer ones to single quotes like this:
Text='<%#Eval("CampCode") %>'
I'm creating an web application with multiple languages.
I've set the culture like this
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(selectedLanguage);
Thread.CurrentThread.CurrentUICulture = new CultureInfo(selectedLanguage);
I've got several language files like "en.resx" and "de.resx".
I can read them from my code behind them like this
var test = GetGlobalResourceObject(Thread.CurrentThread.CurrentUICulture.ToString(), "aboutUsLnk");
But how about from the markup page.
I've been searching the web and most pages is suggesting something like this
<asp:Literal Text='<%$ Resources:Resource, aboutUsLnk %>' runat="server" />
That works if I have a .resx file called Resource but i that's not what I want. What did I miss?
That works if I have a .resx-file called Resource but i thats not what I want. What did I miss?
You are probably looking for local resources and meta:resourcekey attribute.
Local are defined per page (you define exactly the same name as your page for them), you use them for storing resources specific to one page. You create them by adding ASP.NET specific folder (App_LocalResources) and then inside it local resources for each of your pages:
App_LocalResources/{pagename}.resx
And then call for resource objects from resource files (AboutUs.resx, AboutUs.fr-BE.resx,...) from the page markup (AboutUs.aspx) would be something like this:
<asp:Literal Text='About Us' meta:resourcekey="aboutUsLnk" runat="server" />
Global resources which you mentioned are defined accros the whole website (usually you store here resources like "Edit", "Save", etc.) and are usually called as you showed.
Read here for more details: http://msdn.microsoft.com/en-us/magazine/cc163566.aspx
EDIT
Ahh sorry for misunderstanding, you are probably asking how to call your global resources which names differentiate per culture. You can do that in your markup code almost the same as you are doing in code behind, using GetGlobalResourceObject.
Anywhere outside of server controls you can write:
<%= GetGlobalResourceObject(System.Threading.Thread.CurrentThread.CurrentUICulture.ToString(), "aboutUsLnk")%>
To call GetGlobalResourceObject inside of server control attributes you cannot use <%= %>, but you can wrap the server controls around it (in the ones that allow this, like Label for example):
<asp:Label ID="Label1" runat="server"><%= GetGlobalResourceObject(System.Threading.Thread.CurrentThread.CurrentUICulture.ToString(), "aboutUsLnk")%></asp:Label>
Or, you can use the binding syntax:
<asp:Label ID="Label1" runat="server" Text='<%# GetGlobalResourceObject(System.Threading.Thread.CurrentThread.CurrentUICulture.ToString(), "aboutUsLnk")%>'></asp:Label>
Note, that when using the latter you will need to bind your control:
protected void Page_Load(object sender, EventArgs e)
{
Label1.DataBind();
}
EDIT 2
You can wrap the upper code in some helper method to improve code readabilty. In code behind you declare it:
protected string GetResource(string resourceName)
{
return GetGlobalResourceObject(System.Threading.Thread.CurrentThread.CurrentUICulture.ToString(), resourceName).ToString();
}
And in markup you can call it similiar as previous:
<asp:Label ID="Label1" runat="server" Text='<%# GetResource("aboutUsLnk")%>'></asp:Label>
<asp:Label ID="Label2" runat="server"><%= GetResource("aboutUsLnk")%></asp:Label>
i have this code in an itemtemplate in a gridview:
<%# DataBinder.Eval (Container.DataItem, "DiscountAmount")%>
It's a decimal value, and it shows 20.300000000000, which is technically right, but i'd prefer to show 20.30 or 20,30, depending on the culture.
But i've never been a big fan of gridviews, and the DataBinder.Eval and Container.DataItem haven't been good friends either, and i'm lost with how to use it.
it has a special prefix (<%#) and when i type anything other then the original code it's no good, but changing <%# to <%= or <% doesn't seem to work either?
This will also work:
<%#= String.Format("{0, 0:N2}",DataBinder.Eval (Container.DataItem, "DiscountAmount"))%>
Edit: I share your discomfort with declarative databinding syntax. You can accomplish the same thing in code-behind by calling the RowDataBound event and implementing whatever changes you want to make as the data is bound to the GridViewRow.
To do this, you need to wire up the event in the markup by setting OnRowDataBound to the name of your event handler, something like this:
<asp:GridView ID="InvoiceGrid" OnRowDataBound="InvoiceGrid_RowDataBound".....>
Then you create an event handler in code behind with a signature like this:
protected void InvoiceGrid_RowDataBound(object sender, GridViewRowEventArgs e)
The first thing you do in that event handler is test which type of GridViewRow type it is:
if (e.Row.RowType == DataControlRowType.DataRow)....
Then you do whatever formatting you want to do.
For folks happy with declarative markup, this may seem burdensome. But for people who are comfortable writing code, you can do a whole lot more here in code behind.
Did you try this?
<%= String.Format("{0:0,0.00}", DataBinder.Eval (Container.DataItem, "DiscountAmount"))%>
or just
<%# DataBinder.Eval(Container.DataItem, "DiscountAmount", "{0:0,0.00}")
You can read more format options in the article String Format for Double.
There are several ways...some of them stated above and here is another one:
Text='<%# GetFormattedDiscount(Eval("DiscountAmount").ToString())%>'
GetFormattedDiscout is a function in your code-behind where you can do whatever formatting you need and return it as string:
protected void GetFormattedDiscount(string amount){
return String.Format("{0:N2}",amount);
}
Even this should work:
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%#String.Format("{0:n2}",Eval("DiscountAmount")) %>'></asp:Label>
</ItemTemplate>
I am using databinding to iterate through a recordset returned from the database, and one of those recordsets is a comma separated list of items - I'm trying to use a second repeater to display each of those items as a hyperlink. So far this is the code that I have:
<asp:Repeater ID="myRepeater" runat="server" DataSource='<%# DataBinder.Eval(Container.DataItem, "SomeList").ToString().Trim(',') %>'>
<ItemTemplate>
<a href='http://somesite/downloadattachment.aspx?itemid=<%# Container.ItemIndex %>'><%# Container.DataItem %></a>
</ItemTemplate>
</asp:Repeater>
The trouble is that so far there are 3 reasons why this doesnt work:
I get a server tag is not well formed error unless I remove the runat="server" - why is this? (And why does it work without the runat="server"?)
Container.DataItem Evaluates to an instance of System.Data.DataRowView - how do I get the current piece of the string that I split?
More importantly, this only seems to print out 1 Container.DataItem, even when I know there is a comma in the string I've given it - any ideas?
Instead of Eval(), for non-trivial scenarios I generally cast Container.DataItem to the type I want, and then act on it from there in a type-safe way.
The "not well formed" error is caused by the single-quotes around the parameter to Trim(). If you use single quotes on the outside of your attribute definition, you can't use them inside it. In cases like yours where a databinding definition has a lot of code in it, I often create a helper method (either inside a script runat=server for for MVC views and other inline-code-friendly cases, or in code-behind for traditional web forms apps) which handles the code I want to run. By refactoring into a method, it clarifies the HTML and sidesteps the lame single/double-quote restrictions.
Regardless of where you put the code, In your case, you want to:
cast Container.DataItem to DataRowView
extract the SomeList column value using the [] operator
call String.Split() on that string to turn your CSV string it into an array of strings
use that as a data source of your inner repeater
The code should look something like this:
<asp:Repeater ID="myRepeater" runat="server"
DataSource='<%# ((System.Data.DataRowView)Container.DataItem)["SomeList"].ToString().Split(new string[] {","}, StringSplitOptions.RemoveEmptyEntries)%>'>
<ItemTemplate>
<a href='http://somesite/downloadattachment.aspx?itemid=<%# Container.ItemIndex %>'>
<%# Container.DataItem %>
</a>
</ItemTemplate>
</asp:Repeater>
Did you specify the updatecommand, deletecommand to the sqldatasource?
Even if the proper parameters haven't been supplied, the affected rows will always be 0. If it has two parameters for the update command, two parameters have to be supplied through updatecommand.
For more information on this please check this URL: http://www.itpian.com/Coding/4774-Data-binding.aspx
I have a Customer class with a string property comments and I am trying to bind it like this:
<asp:TextBox ID="txtComments"
runat="server"
TextMode="MultiLine" Text=<%=customer.Comments %>>
</asp:TextBox>
However, it gives me the error:
Server tags cannot contain <% ... %> constructs.
I also have a method in the class called GetCreatedDate and in the aspx page, I am doing
<%=GetCreatedDate()%> and <%GetCreatedDate();%>. What is the difference?
Alternatively you can set the value in the Page_Load event of the code behind file:
txtComments.Text = customer.Comments;
you should use "<%# %>" for data binding
<asp:TextBox ID="txtComments"
runat="server"
TextMode="MultiLine" Text="<%# customer.Comments %>">
</asp:TextBox>
Try this instead.
<asp:TextBox ID="txtComments"
runat="server"
TextMode="MultiLine" Text=<%# customer.Comments %>>
</asp:TextBox>
Notice the = to #
Use the DataBinding syntax as stated, <%# customer.Comments %>. This syntax is only evaluated when the TextBox is databound. You would usually use it in a DataBound list. In this case you need to databind the control manually. Override the page's OnDataBinding method and call txtComments.DataBind();
The databinding syntax is the only way to declaratively set ServerControl properties from the aspx page. The Response.Write of the other syntax happens at a time that the ServerControl properties cannot be accessed. If the control is not inside a databound control, you have to databind it.
If you were looking to go all declarative in your page, you don't gain to much using this method because you still need to write code in the code behind.
An alternative if you want to use the TextBox on its own without a parent DataBound control would be to subclass the TextBox, add an AutoBind property, and in the subclassed control call its DataBind method if it is true. That would let you bind the values without writing databinding code in the code behind.
You could also add the TextBox and other form controls to a FormView control and bind it to your object. You can still use the DataBinding syntax in that case.
try this
<asp:TextBox ID="txtComments"
runat="server"
TextMode="MultiLine" Text='<%# customer.Comments %>'>
</asp:TextBox>