When you think ASP, think...
Recent Articles
All Articles
ASP.NET Articles
ASPFAQs.com
Message Board
Related Web Technologies
User Tips!
Coding Tips
Search

Sections:
Book Reviews
Sample Chapters
Commonly Asked Message Board Questions
JavaScript Tutorials
MSDN Communities Hub
Official Docs
Security
Stump the SQL Guru!
Web Hosts
XML
Information:
Advertise
Feedback
Author an Article

ASP ASP.NET ASP FAQs Message Board Feedback
 
Print this Page!
Published: Wednesday, October 2, 2002

Creating a Custom DataGridColumn Class, Part 2

By John Dyer


  • Read Part 1

  • In Part 1 we examined how to truncate a DataGrid's column by using a custom function and a TemplateColumn. In this part we'll look at how to provide the same functionality by rolling our own DataGridColumn class.

    - continued -

    Building our Own DataGridColumn Class


    The solution in Part 1 works very well and does exactly what we wanted it to do. But we may want to use this functionality again in other pages or customize the function further. But each time we make a change, we don't want to have to copy our Truncate(input, characterLimit) function to every page we use it in. A great solution to this problem is to build the Truncate(input, characterLimit) function right into a custom DataGridColumn that we can then use on any page! Inheriting powerful controls like the BoundColumn class and adding new functionality to them is one of the greatest and most powerful features of the .NET Framework.

    To accomplish this we're going to create a new DataGridColumn class called LimitColumn that inherits the BoundColumn class. Due to its being derived from the BoundColumn class, the new DataGridColumn class will have all of the built-in functionality already present in the BoundColumn class. We just need to add one property to it called CharacterLimit and give it a default of 0 so that if CharacterLimit is not set, the column will not do any truncating (that is, it will behave just as if the developer had added a BoundColumn control).

    To provide truncating ability, we are going to override the BoundColumn's FormatDataValue method. The FormatDataValue method is normally used along with the DataFormatString property to format numeric and date information. Essentially we will create our own custom Data Format by using the Truncate(input, characterLimit) function in place of the built-in FormatDataValue method.

    Below is the code for the LimitColumn class. If you are using Visual Studio .NET, create a new C# project of type Class Library and copy in the below code (you will need to add the System.Web.dll assembly in the References section of your project). If you do not have VS.NET, simply create a text file named LimitColumn.cs and copy the following text into it.

    using System;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    
    namespace myNameSpace
    {
      /// <summary>
      /// Summary description for LimitColumn.
      /// </summary>
      
    public class LimitColumn : BoundColumn {
      private int characterLimit = 0;
    
      public int CharacterLimit { 
        get  { return characterLimit; }
        set  { characterLimit=value; }
      }   
      
      protected override string FormatDataValue(object dataValue) {
        return Truncate(dataValue.ToString());
      }
        
        
      string Truncate(string input) {
        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;
      }
    } // End LimitColumn
    } // End myNameSpace
    
    We're now ready to compile this code. If you are using VS.NET go to the Build menu and select Build Project. If you are not using VS.NET you will need to use the compiler from the command prompt. Simply navigate to the directory where the .cs file is and enter:

    csc /t:library /out:LimitColumn.dll LimitColumn.cs

    Regardless of if you are using VS.NET or not you will need to move the created DLL to your Web project's /bin folder. Once the DLL is in the /bin folder we can use the DataGridColumn class we created. First, we need to import the myNameSpace namespace by adding the line :

    <%@ Register TagPrefix="myControls" Namespace="myNameSpace" Assembly="LimitColumn" %>

    to the top of our ASP.NET Web page. Then we can replace the TemplateColumn code with myControls:LimitColumn and set the CharacterLimit property accordingly.

    <%@ Register TagPrefix="myControls" 
                    Namespace="myNameSpace" Assembly="LimitColumn" %>
    
    ...
    
    <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>
    
    [View a Live Demo!]

    Conclusion


    There you have it: Your own custom column that only outputs the amount of text that you want. You could change the truncate function to limit to a number of words or do any other custom formatting that you'd like it to do.

    For More on Custom DataBoundColumn Classes...
    For more code examples on creating your own custom DataGridColumn classes, head on over to MetaBuilders.com. There are a number of complete code examples that can be used to improve the functionality of the DataGrid Web control. (Unfortunately there are no articles or tutorials on the code, just source code comments...)

    Have fun and Happy Programming!

  • By John Dyer



  • ASP.NET [1.x] [2.0] | ASPMessageboard.com | ASPFAQs.com | Advertise | Feedback | Author an Article