I made a function to truncate a string in the code behind file. But how do i use it in the aspx file?
This is the textbox:
<asp:TemplateField HeaderText="page" HeaderStyle-Wrap="true">
<ItemTemplate>
<a href='<%# makepageURL( Eval("page") )%> '>
<%# Eval("page")%>
</a>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtpage" TextMode="SingleLine" Rows="1" Width="100%" runat="server" Text='<% #Bind("page") %>' />
</EditItemTemplate>
</asp:TemplateField>
And this is my function:
Public Function TrimString(ByVal Value As String, ByVal Length As Integer) As String
If Value.Length > 20 Then
Return Value.Substring(Value.Length - (20 - 3)) + "..."
End If
Return Value
End Function
It's not an issue of how to use it, but actually when to use it?
If you had a regular span, you could do this:
<span><%: TrimString("somestring") %></span>
But this is a TextBox your dealing with (user input).
When should it truncate?
On Form Submit? (that would make sense).
As they type (well then you'd need to use JavaScript).
By the looks of your code snipper, your using a FormView.
So i wouldn't be calling it from the ASPX (which the equivalent of executing code during Page Render), i would be calling it during the Edit/Submit event, server-side event handler.
In other words, truncate the value the user put in, after they have submitted the form and before you persist to the database.
Related
From an aspx page, I am trying to display a user control for each item in a collection, but the C# seems to be ignored when tryign to set the UserControl parameter:
<%foreach (Fetus item in this.pregnancy.Fetus) {%>
//this returns a GUID:
"<%= item.Id.ToString() %>"
//this does not work, returns the characters between "" like < %= item.Id.ToString()%>:
<uc1:AntepartumCTGChart runat="server" ID="AntepartumCTGChart" FetusId="<%= item.Id.ToString()%>" />
<% } %>
I would expect this to work, what's wrong?
You have to use a data binding expression
<uc1:AntepartumCTGChart runat="server" ID="AntepartumCTGChart" FetusId='<%# item.Id.ToString()%>' />
But you have to call DataBind() in code behind for that to work.
You can also use a Repeater
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<uc1:AntepartumCTGChart runat="server" ID="AntepartumCTGChart" FetusId='<%# Eval("id").ToString()%>' />
</ItemTemplate>
</asp:Repeater>
And then bind data to it in code behind
Repeater1.DataSource = pregnancy.Fetus;
Repeater1.DataBind();
I think this is not possible by trying to add a literal into a footer template of a repeater so that I can fill it later on...
<FooterTemplate>
<asp:Literal ID="panelFooter" runat="server"></asp:Literal>
</FooterTemplate>
You can data bind the Text attribute to the result of a method in your code-behind. In this example we are going to display the total number of products in the footer:
<FooterTemplate>
Total number of products:
<asp:Literal runat="server" Text='<%# GetTotalNumberOfProducts() %>' />
</FooterTemplate>
In the code-behind we are going to create a method that calculates the number and returns it for the Literal control.
protected string GetTotalNumberOfProducts()
{
return 42.ToString();
}
Notice that we don't need to find the control by its ID. We are just returning s string and the data binding syntax will call our method in code-behind and put the result inside the control.
A basic question but there is no such question on Stack Overflow (for ASP.NET)
<asp:TextBox ID="txtUserName" runat="server" Text=<% Session["UserName"] %> >
I did this a week ago, now something is wrong. It should be simple. I also tried <%= %>, it did not work either. Putting a single quote around '<% %>' gives binding error. Help
I normally hide the implementation details from the aspx code with a property:
.cs file
public string UserName { get { return Session["UserName"]; } }
.aspx
<asp:TextBox ID="txtUserName" runat="server" Text='<%= UserName %>' >
What I did was pulled the text box in C# code and set it text value to the session.
Example:
txtUserName.text = Session["UserName"];
Use it in one of the function which checks the session values or you can use in page_load function (the default function for every page)
Now I think your code should look like <asp:TextBox ID="txtUserName" runat="server" Text='<%# Session["UserName"] %>' >
I always forget the sintax for inline code, this information could be helpfull I think.
i have a bit of aspx code that uses Eval to generate a call to a javascript function:
ASP.NET (wrapped for readability):
<asp:LinkButton runat="server"
OnClientClick='<%# Eval(
"NodeGUID",
"return DoStuff(this, \"{0}\");") %>'
Text="Do stuff" />
this generates javascript similar to:
Javascript (wrapped for readability):
return DoStuff(this,
"3F2504E0-4F89-11D3-9A0C-0305E82C3301"
);
Note: i've converted the generated " entities references into quotes for readability.
i now need to add a 3nd parameter to the javascript function call, a caption:
Javascript (wrapped for readability)
return DoStuff(this,
"3F2504E0-4F89-11D3-9A0C-0305E82C3301",
"AllisonAngel.jpg"
);
Note: i've converted the generated " entities references into quotes for readability.
There already exists a function in the code-behind file that is used to return the caption for an item:
C# (code omitted for readability):
protected string GetItemText(MySomething item)
{
...
}
i know that the above function can be called from the aspx file using a syntax similar to:
ASP.NET (wrapped, code omitted, for readability):
<asp:LinkButton ... runat="server"
Text="<%# GetItemText((MySomething)Container.DataItem) %>"
... />
So now i want to use this function to include the 3rd parameter to the javascript function.
Starting from:
<asp:LinkButton runat="server"
OnClientClick='<%# Eval(
"NodeGUID",
"return DoStuff(this, \"{0}\", \"Todo - Insert caption here\");") %>'
Text="Do stuff" />
i need to change: "Todo - Insert caption here"
into a call to: <%# GetItemText((MySomething)Container.DataItem) %>
Blindly trying the obvious:
ASP.NET (wrapped for readability):
<asp:LinkButton runat="server"
OnClientClick='<%# Eval(
"NodeGUID",
GetItemText((MySomething)Container.DataItem),
"return DoStuff(this, \"{0}\", \"{1}\");") %>'
Text="Do stuff" />
But that complains, since Eval() only takes two parameters.
i tried the slightly less obivous:
ASP.NET (wrapped for readability)
<asp:LinkButton runat="server"
OnClientClick='<%# Eval(
"NodeGUID",
"return DoStuff(this,
\"{0}\",
\""+GetItemText((MySomething)Container.DataItem)+"\");") %>'
Text="Do stuff" />
But that doesn't work either.
Related Questions
ASP.NET: How to access repeater generated elements from javascript?
asp.NET: How to access repeater generated elements?
The trick isn't to pass multiple items to an eval, but to pass multiple eval's to whatever you want to use to format the data. You could also have just done it this way - which would have kept the presentation in the aspx file like you wanted...
<asp:LinkButton
runat="server"
OnClientClick='<%# string.Format(
"return DoStuff(this, \"{0}\", \"{1}\");",
Eval("NodeGUID"),
GetItemText((MySomething)Container.DataItem)) %>'
Text="Do stuff" />
My Trick
Eval("FLName", Eval("FLFDID","{0}")+"/{0}")
Eval inside Eval
It Work for me !!
Robert C. Barth gave me the idea that solves the problem:
<asp:LinkButton runat="server"
OnClientClick="<%# GetItemClientClick((MySomething)Container.DataItem) %>"
Text="Do stuff" />
and then the code-behind file contains:
protected string GetItemClientClick(MySomething item)
{
...
String szOnClientClick =
"return DeleteItem(this, "+
Toolkit.QuotedStr(item.NodeGUID.ToString()) + ", "+
Toolkit.QuotedStr(GetItemText(item))+");";
return szOnClientClick;
}
i really would have preferred to keep presentation in the aspx, and business logic in the code-behind - but the real world often doesn't conform to that model.
If the LinkButton is not inside some other thing (like a grid), just set the OnClientClick attribute in the code-behind like normal, using string.Format.
If it IS in a grid (or repeater, or something of that nature), set it in the RowDataBound event using FindControl or e.Row.Cells[] and string.Format. If you use e.Row.Cells[], you can probably dump the LinkButton server control and just output a normal anchor tag.
Continued from Scott Ivey's solution, you can also use this to include if statements in your Eval statement:
For example the below will output an anchor tag if the property Url exists, otherwise it will output a span.
<%# string.Format(Eval("Url") != null ? "{1}" : "<span>{1}</span>", Eval("Url"), Eval("Text")) %>">
you can try this
'<'asp:HyperLink ID="hp" runat="server" CommandArgument='<%# Eval("SysID", "{0}")%>'
NavigateUrl='<%# String.Format("~/ReportViewer.aspx?RevID= {0}
& User={1}", Eval("ID"), Eval("USER")) %>' Target="_blank" %>'>
</asp:HyperLink>
http://afzal-gujrat.blogspot.com/2012/10/pass-more-evals-in-querystring-with.html
How can I format data coming from a DataBinder.Eval statement in an ASPX page?
For example, I want to display the published date of the news items in a particular format in the homepage. I'm using the ASP.NET 2.0 Repeater control to show the list of news items.
The code for this goes like this:
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="ObjectDataSource1">
<HeaderTemplate><table cellpadding="0" cellspacing="0" width="255"></HeaderTemplate>
<ItemTemplate>
<tr><td >
<a href='/content/latestNews.aspx?id=<%#DataBinder.Eval(Container.DataItem, "id") %>'>
<asp:Label ID="lblNewsTitle" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "title") %>'></asp:Label>
</a>
</td></tr>
<tr><td>
<asp:Label ID="lblNewsDate" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "publishedDate"))%>'></asp:Label>
</td></tr>
</ItemTemplate>
<FooterTemplate></table></FooterTemplate></asp:Repeater>
Is there a way I could call a custom method with the DataBinder.Eval value as its parameter (something like below)?
<asp:Label ID="lblNewsDate" runat="server" Text='<%# GetDateInHomepageFormat(DataBinder.Eval(Container.DataItem, "publishedDate")) )%>'></asp:Label>
If yes, then where do I write the GetDateInHomepageFormat method? I tried out in the code behind page but got a run time error?
If this is not possible, is there a way to do inline formatting?
There is an optional overload for DataBinder.Eval to supply formatting:
<%# DataBinder.Eval(Container.DataItem, "expression"[, "format"]) %>
The format parameter is a String value, using the value placeholder replacement syntax (called composite formatting) like this:
<asp:Label id="lblNewsDate" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "publishedDate", "{0:dddd d MMMM}") %>'</label>
After some searching on the Internet I found that it is in fact very much possible to call a custom method passing the DataBinder.Eval value.
The custom method can be written in the code behind file, but has to be declared public or protected. In my question above, I had mentioned that I tried to write the custom method in the code behind but was getting a run time error. The reason for this was that I had declared the method to be private.
So, in summary the following is a good way to use DataBinder.Eval value to get your desired output:
default.aspx
<asp:Label ID="lblNewsDate" runat="server" Text='<%# GetDateInHomepageFormat(DataBinder.Eval(Container.DataItem, "publishedDate")) )%>'></asp:Label>
default.aspx.cs code:
public partial class _Default : System.Web.UI.Page
{
protected string GetDateInHomepageFormat(DateTime d)
{
string retValue = "";
// Do all processing required and return value
return retValue;
}
}
Hope this helps others as well.
Why not use the simpler syntax?
<asp:Label id="lblNewsDate" runat="server" Text='<%# Eval("publishedDate", "{0:dddd d MMMM}") %>'</label>
This is the template control "Eval" that takes in the expression and the string format:
protected internal string Eval(
string expression,
string format
)
http://msdn.microsoft.com/en-us/library/3d2sz789.aspx
You can use a function into a repeater like you said, but notice that the DataBinder.Eval returns an object and you have to cast it to a DateTime.
You also can format your field inline:
<%# ((DateTime)DataBinder.Eval(Container.DataItem,"publishedDate")).ToString("yyyy-MMM-dd") %>
If you use ASP.NET 2.0 or newer you can write this as below:
<%# ((DateTime)Eval("publishedDate")).ToString("yyyy-MMM-dd") %>
Another option is to bind the value to label at OnItemDataBound event.
This line solved my problem:
<%#DateTime.Parse(Eval("DDDate").ToString()).ToString("dd-MM-yyyy")%>
To format the date using the local date format use:
<%#((DateTime)Eval("ExpDate")).ToString("d")%>
How to Format an Eval Statement to Display a Date using Date Locale
Thanks to all. I had been stuck on standard format strings for some time. I also used a custom function in VB.
Mark Up:-
<asp:Label ID="Label3" runat="server" text='<%# Formatlabel(DataBinder.Eval(Container.DataItem, "psWages1D")) %>'/>
Code behind:-
Public Function fLabel(ByVal tval) As String
fLabel = tval.ToString("#,##0.00%;(#,##0.00%);Zero")
End Function
Text='<%# DateTime.Parse(Eval("LastLoginDate").ToString()).ToString("MM/dd/yyyy hh:mm tt") %>'
This works for the format as you want
<asp:Label ID="ServiceBeginDate" runat="server" Text='<%# (DataBinder.Eval(Container.DataItem, "ServiceBeginDate", "{0:yyyy}") == "0001") ? "" : DataBinder.Eval(Container.DataItem, "ServiceBeginDate", "{0:MM/dd/yyyy}") %>'>
</asp:Label>
You can use it this way in aspx page
<%# DataBinder.Eval(Container.DataItem, "DateColoumnName", "{0:dd-MMM-yyyy}") %>