首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> ASP.NET 基礎

ASP.NET GridView 列寬固定不被內容撐大的 4 種實用方法

     編輯:ASP.NET 基礎

前言

GridView 預設會依內容自動調整列寬,導致版面突變。本文提供 4 種固定列寬的技巧,從 CSS 全域控制到欄位屬性微調,滿足不同場景需求。

方法一: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 才能強制生效,否則瀏覽器仍可能因內容撐大。

方法三:移除 GridView 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。
  • 百分比寬度總和超過 100%:會導致最後幾欄擠壓,建議總和 ≤ 95% 或混用像素。

結語

核心原則:CSS table-layout: fixed 為基礎,欄位 Width 為輔,overflow: hidden 保護版面。依專案需求組合上述方法,即可獲得穩定、美觀的 GridView 表格。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved