I have to set maximum length for bound field in an editable gridview. For this i have used data format string property and also given ApplyFormatInEditMode="true" still it accepts invalid input. The gridview does not have template field, it contains bound fields only. I have written OnRowEditing and RowUpdating events. The dataformat string is DataFormatString="{0:N0}" but it accepts '2352345234523454352345' input also and displays server error while updating in database. I want to spcify maximum length for the textboxes generated dynamically when Edit button is clicked.
DataFormatString
does not handle the MaxLength
. Try using DataBinder.Eval()
inside textbox, and set the MaxLength
there. Like following:
<asp:TemplateField HeaderText="My Text">
<ItemTemplate>
<asp:TextBox ID="txtID" MaxLength="10" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "YOUR_BOUND_ITEM_NAME") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
--EDIT--
asp:BoundField
by its nature display the records. So there is no way you can set the MaxLength of it.
I have to set maximum length for bound field in an editable gridview.
You can grab the edit_button_click(or which ever event) event that shows the text box in the grid. There you can set the MaxLength of text box.
Alternatively, This example might help.
I have done this by writing the following code in Rowdatabound event in gridview. In this event, I have implicitly converted gridview cells to dynamically generated textboxes and set width and Max length for them. In key press event, i have blocked alphabets and other special characters from being entered in the textbox. Now it works fine as expected!. The code is as follows:
if (e.Row.RowType == DataControlRowType.DataRow) {
for (int i = 1; i < dgv.Columns.Count - 1; i++)
{
if ((e.Row.Cells[i].Controls.Count > 0) && (e.Row.Cells[i].Controls[0].GetType().ToString() == (new TextBox()).ToString()))
{
((TextBox)e.Row.Cells[i].Controls[0]).Width = 40;
((TextBox)e.Row.Cells[i].Controls[0]).MaxLength = 5;
}
}
}
//To make the text box accept numbers, delete, backspace, numlock,dot only
e.Row.Attributes.Add("onkeypress", "javascript: var Key = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode; return ((Key >= 48 && Key <= 57) || (Key == 110) || (Key == 190) || (Key == 8) || (Key == 46) || (Key == 144))");