In an ASP.NET GridView is it possible to truncate the displayed text but yet keep the whole string so that it can be displayed in a tooltip on hover over?
I have a code behind function written as follows:
public static string TruncateString(string stringToTruncate, int length)
{
return stringToTruncate.Length > length ?
stringToTruncate.Substring(0, length) + "..." :
stringToTruncate;
}
Switching to the .aspx page I have a GridView created thereon. This is bound to the contents of a custom object which is filled from the results of a sproc.
For the purposes of this let’s assume the field is called BigNVarCharField, autogeneration of columns is turned off and the usual GridView markup is in place.
<asp:BoundField DataField="BigNVarCharField" HeaderText="Big field preview" Visible="true">
I thought that I should be able to do something like use the DataFormatString attribute thus but it doesn’t seem to be working
DataFormatString = '<%#HelperFunctions.TruncateString(Convert.ToString(Eval("BigNVarCharField")))%>'
I don’t want to truncate it in the database or the business logic as I want to be able to display it in a tooltip on hover over the column in question.
The site is already using jQuery so that can be used for the tooltip if needs be.
EDIT: 2011-04-23 How it worked out finally
<asp:TemplateField HeaderText="Big field preview">
<EditItemTemplate>
<asp:TextBox ID="txtBigNVarCharField" runat="server" Text='<%# Bind("BigNVarCharField") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblBigNVarCharField" runat="server" Text='<%# HelperFunctions.TruncateString(DataBinder.Eval(Container.DataItem,"BigNVarCharField").ToString(), 50)%>' ToolTip='<%#Eval("BigNVarCharField")%>'></asp:Label>
</ItemTemplate>
Marking Chad’s one as the accepted answer as that was what steered me in the correct direction.
Convert this to a template field then insert your as label text. I would probably use the row databound event to handle the logic but you may be able to accomplish it in the markup.
The DataFormatString is good for numbers and dates but will not do what you are looking for.