GridView 預設會依內容自動調整列寬,導致版面突變。本文提供 4 種固定列寬的技巧,從 CSS 全域控制到欄位屬性微調,滿足不同場景需求。
table-layout: fixed + overflow: hidden(最徹底)在頁面或母版頁加入:
<style>
.fixed-grid { table-layout: fixed; width: 100%; }
.fixed-grid td { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
</style>
GridView 套用 CssClass="fixed-grid"。
效果:所有列嚴格遵守宣告寬度,超出內容自動截斷並顯示省略號。
HeaderStyle-Width / ItemStyle-Width(百分比或像素)<asp:BoundField DataField="Title" HeaderText="標題" >
<HeaderStyle Width="30%" />
<ItemStyle Width="30%" />
</asp:BoundField>
或像素:Width="200px"。
注意:需搭配方法一的 table-layout: fixed 才能強制生效,否則瀏覽器仍可能因內容撐大。
Height 屬性 + RowDataBound 固定行高若設定 Height 導致空白行高固定,建議移除該屬性,改用:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Style["height"] = "43px"; // 或 CSS class
}
}
ItemStyle 設定寬度<asp:GridView ID="GridView1" AutoGenerateColumns="False" runat="server">
<Columns>
<asp:BoundField DataField="Id" HeaderText="ID">
<ItemStyle Width="80px" />
</asp:BoundField>
<asp:BoundField DataField="Name" HeaderText="名稱">
<ItemStyle Width="200px" />
</asp:BoundField>
</Columns>
</asp:GridView>
<asp:GridView ID="gvList" CssClass="fixed-grid" AutoGenerateColumns="False" runat="server">
<Columns>
<asp:BoundField DataField="Id" HeaderText="ID">
<HeaderStyle Width="60px" /><ItemStyle Width="60px" />
</asp:BoundField>
<asp:BoundField DataField="Title" HeaderText="標題">
<HeaderStyle Width="40%" /><ItemStyle Width="40%" />
</asp:BoundField>
<asp:BoundField DataField="CreateTime" HeaderText="建立時間">
<HeaderStyle Width="150px" /><ItemStyle Width="150px" />
</asp:BoundField>
</Columns>
</asp:GridView>
<style>
.fixed-grid { table-layout: fixed; width: 100%; border-collapse: collapse; }
.fixed-grid th, .fixed-grid td {
overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
padding: 5px; border: 1px solid #ddd;
}
</style>
table-layout: fixed:瀏覽器採用自動演算法,寬度屬性僅為建議值。white-space: nowrap 會強制不換行,若需換行請改用 word-break: break-all 並移除 nowrap。核心原則:CSS table-layout: fixed 為基礎,欄位 Width 為輔,overflow: hidden 保護版面。依專案需求組合上述方法,即可獲得穩定、美觀的 GridView 表格。