萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

ASP.NET GridView 自動換行設定:CSS word-break 與 word-wrap

RowDataBound 事件統一設定

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    // 讓所有儲存格內容自動換行
    GridView1.Attributes.Add("style", "word-break:break-all; word-wrap:break-word;");
}

CSS 屬性說明

屬性值效果
word-breakbreak-all單字內任意處換行 (適合中文/連續英文/數字)
word-wrap / overflow-wrapbreak-word單字過長超出容器時強制換行
white-spacenormal預設,允許換行;若設為 nowrap 則不換行

進階:針對特定欄位設定

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        // 僅第 2 欄 (索引 1) 自動換行
        e.Row.Cells[1].Attributes.Add("style", "word-break:break-all; word-wrap:break-word;");
        
        // 或加入 CSS Class
        e.Row.Cells[1].CssClass = "auto-wrap";
    }
}

CSS Class 寫法 (建議)

<style>
.auto-wrap { word-break: break-all; word-wrap: break-word; }
</style>

常見問題

  • 設定後不生效:確認 GridView 未設定 ItemStyle-Wrap="false" 或 CSS 被覆寫,用瀏覽器開發工具檢查最終樣式。
  • 表格寬度撐大:搭配 table-layout: fixed; width: 100%; 讓表格遵守容器寬度。
  • Header 不換行:另行設定 HeaderStyle.CssClass。
copyright © 萬盛學電腦網 all rights reserved