It is so easy to limit the number of characters allowed in a normal textbox by using MaxLength property, But same doesn’t work if the TextMode property of textbox is set to Multiline.
By default TextMode = "SingleLine" for a normal textbox, and it gets rendered as an input type textbox and when we set its TextMode property to MultiLine, it gets rendered as a textarea.
Note: MaxLength property works only for input type and not for textarea. So to handle this, either you can use JavaScript, jQuery or any other scripts. But in this article I used C# to handle this.
So let's take an example, and take one normal textbox and one multiline textbox and see differences before and after writing codebehind.
.aspx:
- <asp:TextBox ID="txtMultiLine" runat="server" TextMode="MultiLine" MaxLength="5"></asp:TextBox>
- <br />
- <asp:TextBox ID="txtNormal" runat="server" MaxLength="5"></asp:TextBox>
CodeBehind:
- using System;
- using System.Web.UI;
-
- namespace Maxlength
- {
- public partial class MacLength : System.Web.UI.Page
- {
- protected void Page_Load(object sender, EventArgs e)
- {
- if (!Page.IsPostBack)
- {
- txtMultiLine.Attributes.Add("maxlength", txtMultiLine.MaxLength.ToString());
- }
- }
- }
- }
I hope you enjoyed it. Please provide your valuable suggestions and feedback.