RowDataBound 事件統一設定
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
// 讓所有儲存格內容自動換行
GridView1.Attributes.Add("style", "word-break:break-all; word-wrap:break-word;");
}
CSS 屬性說明
| 屬性 | 值 | 效果 |
| word-break | break-all | 單字內任意處換行 (適合中文/連續英文/數字) |
| word-wrap / overflow-wrap | break-word | 單字過長超出容器時強制換行 |
| white-space | normal | 預設,允許換行;若設為 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。