I was surprised the day I wanted to delimit a textbox in row edition(gridview) and avoid the user to enter unnecessary characters in my textbox. A simple boundfield is not fit to support that and custom code is necessary.
So I have written a long time ago a simple class with C#2 that I used when a define some gridview columns : LimitedBoundField.
public class LimitedBoundField : BoundField
{
private int _characterLimit = 0;
private int _textBoxWidth = 100;
public int MaxLength
{
get { return _characterLimit; }
set { _characterLimit = value; }
}
public int TextBoxWidth
{
get { return _textBoxWidth; }
set { _textBoxWidth = value; }
}
public override void InitializeCell(DataControlFieldCell cell, DataControlCellType cellType, DataControlRowState rowState, int rowIndex)
{
base.InitializeCell(cell, cellType, rowState, rowIndex);
if (cellType == DataControlCellType.DataCell)
{
if (rowState == DataControlRowState.Edit ||
rowState == (DataControlRowState.Normal | DataControlRowState.Edit) ||
rowState == (DataControlRowState.Alternate | DataControlRowState.Edit))
{
if (cell.Controls.Count > 0 && cell.Controls[0] is TextBox)
{
TextBox tb = ((TextBox)cell.Controls[0]);
if(MaxLength>0)
tb.MaxLength = MaxLength;
tb.Width = TextBoxWidth;
tb.Text = tb.Text.Substring(0, (tb.Text.Length > _characterLimit) ? _characterLimit : tb.Text.Length);
}
}
}
}
}