Using a TemplateColumn to Truncate the Length of a Database Field

This demo lists the ID and Description of the 10 most viewed FAQs on ASPFAQs.com. However, the Description column is truncated to 10 characters. Logic is used to not truncate a string such that a word is cut in half. You can compare the results below with the BoundColumn demo. column in the DataGrid.


IDFAQ Description
181 How can I...
161 How can I...
115 I am using...
83 How can I...
190 How do I...
106 How can I...
118 When I get...
30 For...
14 Can I send...
149 How can I...


Source Code:
<% @Import Namespace="System.Data" %>
<% @Import Namespace="System.Data.SqlClient" %>
<script language="C#" runat="server">
  void Page_Load(Object sender, EventArgs e)
  {
    BindData();
  }
	
	
  void BindData()
  {
    // 1. Create a connection
    SqlConnection myConnection = new SqlConnection(ConfigurationSettings.AppSettings["connectionString"]);

    // 2. Create the command object, passing in the SQL string
    const string strSQL = "sp_Popularity";
    SqlCommand myCommand = new SqlCommand(strSQL, myConnection);

    // Set the datagrid's datasource to the datareader and databind
    myConnection.Open();
    FAQs.DataSource = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
    FAQs.DataBind();
  }
  
	string Truncate(string input, int characterLimit) {
	  string output = input;

	  // Check if the string is longer than the allowed amount
	  // otherwise do nothing
	  if (output.Length > characterLimit && characterLimit > 0) {

	    // cut the string down to the maximum number of characters
	    output = output.Substring(0,characterLimit);

	    // Check if the space right after the truncate point was a space
	    // if not, we are in the middle of a word and need to cut out the rest of it
	    if (input.Substring(output.Length,1) != " ") {
	      int LastSpace = output.LastIndexOf(" ");

	      // if we found a space then, cut back to that space
	      if (LastSpace != -1) {
	        output = output.Substring(0,LastSpace);  
	      }
	    }
	    // Finally, add the "..."
	    output += "...";    
	  }
	  return output;
	}  
</script>

<form runat="server">
  <asp:DataGrid id="FAQs" runat="server" 
    AutoGenerateColumns="False" CellPadding="2"
    HeaderStyle-BackColor="Black"
    HeaderStyle-ForeColor="White"
    HeaderStyle-HorizontalAlign="Center"
    HeaderStyle-Font-Bold="True">
  <Columns>
    <asp:BoundColumn HeaderText="ID" DataField="FAQID"  />
	<asp:TemplateColumn HeaderText="FAQ Description">
	  <ItemTemplate>
	    <%# Truncate(DataBinder.Eval(Container.DataItem, "Description").ToString(), 10) %>
	  </ItemTemplate>
	</asp:TemplateColumn>
  </Columns>
  </asp:datagrid>
</form>


[Return to the article]