This documentation is archived and is not being maintained.

StringLengthAttribute Class

Updated: July 2008

Specifies the maximum length of characters that are allowed in a data field.

Namespace:  System.ComponentModel.DataAnnotations
Assembly:  System.ComponentModel.DataAnnotations (in System.ComponentModel.DataAnnotations.dll)

<AttributeUsageAttribute(AttributeTargets.Property Or AttributeTargets.Field, AllowMultiple := False)> _
Public Class StringLengthAttribute _
	Inherits ValidationAttribute
Dim instance As StringLengthAttribute

ASP.NET Dynamic Data enables CRUD (Create, Read, Update and Delete) operations in a data model. You can specify the maximum length of characters of each field when inserting and updating data. For character data types, the MaximumLength property identifies the greatest number of bytes required to store a string. If the maximum number of characters is less than 0, the StringLengthAttribute constructor throws an [ArgumentOutOfRangeException].

The following code example limits the number of characters of the ThumbnailPhotoFileName field in the Products Table in AdventureWorksLT database to 4, by applying the StringLength attribute to the Products partial class that represents the Products table.

<MetadataType(GetType(ProductMetadata))> _ 
Public Partial Class Product 

End Class  

Public Class ProductMetadata 

    <ScaffoldColumn(True)> _ 
    <StringLength(10, ErrorMessage := "The file name cannot exceed 10 characters long")> _ 
    Public ProductNumber As Object 

End Class

To compile the example code, you need the following:

  • Visual Studio 2008 Service Pack 1 or Visual Developer 2008 Express Edition Service Pack 1.

  • The AdventureWorksLT sample database. For information about how to download and install the SQL Server sample database, see Microsoft SQL Server Product Samples: Database on the CodePlex site. Make sure that you install the correct version of the sample database for the version of SQL Server that you are running (SQL Server 2005 or SQL Server 2008).

  • A Dynamic Data Web site. This enables you to create a data context for the database and the class that contains the data field to customize and the methods to override. In addition, it creates the environment in which to use the page described before. For more information, see Walkthrough: Creating a New Dynamic Data Web Site using Scaffolding.


Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Windows 7, Windows Vista, Windows XP SP2, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003

The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

.NET Framework

Supported in: 3.5 SP1




July 2008

Added topic for new class.

SP1 feature change.