how should we restrict characters typed in a control to its width only.
Printable View
how should we restrict characters typed in a control to its width only.
Put an event handler in for the "TextChanged" event.
Then, get the text out of the text box and measure it.
I'd have an inherited class to do this :
I've not tried this out, but it should give you a rough idea of how to do it.Code:public class WidthLimitTextBox : TextBox
{
private string m_sOldText = "";
private bool m_fHandleTextChanged = true;
protected override OnTextChanged(EventArgs e)
{
if (m_fHandleTextChanged)
{
m_fHandleTextChanged = false;
using (Graphics graphics = this.CreateGraphics())
{
Size sizeText = graphics.MeasureString(this.Text, this.Font).ToSize();
if (sizeText.Width > this.ClientRectangle.Width)
{
this.Text = m_sOldText;
}
else
{
m_sOldText = this.Text;
}
}
m_fHandleTextChanged = true;
}
}
}
Darwen.
There is a maxlength attribute for the html textboxes. I am not sure about the server side controls but u might need to write some javascript validations to restrict the user from doing this. The server side control has a size property though, that sets or returns the expected length of the specified text box, in characters. The default value for the size of a text box is 0, which means that the browser will use its default text box length.Quote:
Originally Posted by MSDN