You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 20:40:25