TextBox allows Text more than the MaxLength when Text is Assigned

心已入冬 提交于 2021-02-05 09:26:12

问题


TextBox's MaxLength was set to 5. It works fine that it does not allows to enter or paste the Text more than the MaxLength. But it allows when the Text is assigned from code.

Is it the behavior of TextBox? If it so, How to handle it in a generic way?


回答1:


Is it the behaviour of TextBox?

yes, it is behaviour of text box. From MSDN

This property does not affect characters that are added programmatically.

How to handle it in a generic way?

You can control it progmatically by first checking the length of string and then assigning. Like,

if(stringtoAssign.Length > yourTextBox.MaxLength )
{
    //or throw an exception, mesagebox. What ever you want
    yourTextBox.Text = stringToAssign.SubString(0,yourTextBox.MaxLength);
}



回答2:


FROM MSDN:

TextBox.MaxLength Property

You can use this property to restrict the length of text entered when the data is to be stored in a database so that the text entered into the control does not exceed the maximum length of the corresponding field in the database.

TextBox.MaxLength property does not affect characters that are added programmatically.

Read more here.



来源:https://stackoverflow.com/questions/22555033/textbox-allows-text-more-than-the-maxlength-when-text-is-assigned

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!