如何在ASP.NET(VB)的GridView编辑文本框中实现文本换行?
解决GridView编辑时Comments列文本不换行、居中问题
问题根源是:默认的BoundField在编辑模式下生成的是单行TextBox(TextMode="SingleLine"),即便调整ControlStyle的尺寸,它依然不会自动换行,且默认文本居中。要解决这个问题,必须将该列改为TemplateField,自定义编辑模板使用多行TextBox。
修改步骤:
- 替换原Comments列的
BoundField为TemplateField - 在
TemplateField中分别定义ItemTemplate(显示状态)和EditItemTemplate(编辑状态) - 编辑状态下使用
TextMode="MultiLine"的TextBox,设置左对齐、自动换行及尺寸
修改后的Comments列代码:
<asp:TemplateField HeaderText="Comments" SortExpression="comments"> <HeaderStyle BorderColor="#003960" /> <ItemStyle BorderColor="#003960" Width="250px" HorizontalAlign="Left" VerticalAlign="Middle" Wrap="true" /> <!-- 显示状态的模板 --> <ItemTemplate> <asp:Label ID="lblComments" runat="server" Text='<%# Bind("comments") %>' Width="240px" Wrap="true"></asp:Label> </ItemTemplate> <!-- 编辑状态的模板 --> <EditItemTemplate> <asp:TextBox ID="txtComments" runat="server" Text='<%# Bind("comments") %>' TextMode="MultiLine" Width="240px" Height="400px" TextAlign="Left" Wrap="true"></asp:TextBox> </EditItemTemplate> </asp:TemplateField>
关键属性说明:
TextMode="MultiLine":将TextBox设置为多行模式,支持自动换行Wrap="true":开启文本自动换行TextAlign="Left":设置文本左对齐,解决居中问题Bind("comments"):实现数据双向绑定,确保编辑后的内容能正常保存
替换后,点击编辑按钮时Comments列会显示多行文本框,支持自动换行且文本左对齐,同时保留原有的样式和数据绑定功能。
内容的提问来源于stack exchange,提问作者Paul
相关产品推荐
相关产品推荐

