Using the LimitColumn Class 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 50 characters through the use of a custom DataGridColumn class. The logic that is used to truncate is contained in the class itself, hence the reason this page does not contain any sort of Truncate function as was the case in the previous demo.


IDFAQ Description
181How can I format numbers and date/times using...
161How can I convert a Recordset into an array? ...
115I am using Access and getting a 80004005 error (or...
83How can I quickly sort a VBScript array?
190How do I display data on a web page using arrays...
106How can I find out if a record already exists in a...
118When I get a list of all files in a directory via...
30For session variables to work, must the Web...
14Can I send emails without using CDONTS?
149How can I remove multiple spaces between words in...


Source Code:
<%@ Register TagPrefix="myControls" 
                Namespace="myNameSpace" Assembly="LimitColumn" %>
<% @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();
  }
  
</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"  />
	<myControls:LimitColumn HeaderText="FAQ Description" 
            DataField="Description" CharacterLimit="50"	/>
  </Columns>
  </asp:datagrid>
</form>


[Return to the article]