萬盛學電腦網

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

ASP.NET GridView 固定欄寬完整解決方案:四大實用技巧

問題背景

GridView 自動產生欄位時,欄寬會隨內容撐大,導致版面跑版。需固定欄寬並處理溢位內容。

技巧一:CSS table-layout: fixed (最簡單、最有效)

<style>
    .fixed-grid { table-layout: fixed; width: 100%; }
    .fixed-grid td { 
        overflow: hidden; 
        text-overflow: ellipsis; 
        white-space: nowrap; 
        padding: 5px; 
    }
</style>

<asp:GridView ID="GridView1" runat="server" CssClass="fixed-grid" AutoGenerateColumns="False">
    <Columns>
        <asp:BoundField DataField="id" HeaderText="ID" ItemStyle-Width="50px" />
        <asp:BoundField DataField="title" HeaderText="標題" ItemStyle-Width="300px" />
        <asp:BoundField DataField="date" HeaderText="日期" ItemStyle-Width="120px" />
    </Columns>
</asp:GridView>

關鍵:`

` 加 `table-layout: fixed`,`
` 加 `overflow:hidden; text-overflow:ellipsis; white-space:nowrap`,寬度由 `ItemStyle-Width` 或 `HeaderStyle-Width` 決定。

技巧二:HeaderStyle / ItemStyle 百分比寬度

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
    <Columns>
        <asp:BoundField DataField="id" HeaderText="ID">
            <HeaderStyle Width="10%" />
            <ItemStyle Width="10%" />
        </asp:BoundField>
        <asp:BoundField DataField="name" HeaderText="名稱">
            <HeaderStyle Width="40%" />
            <ItemStyle Width="40%" />
        </asp:BoundField>
        <asp:BoundField DataField="status" HeaderText="狀態">
            <HeaderStyle Width="20%" />
            <ItemStyle Width="20%" />
        </asp:BoundField>
        <asp:BoundField DataField="action" HeaderText="操作">
            <HeaderStyle Width="30%" />
            <ItemStyle Width="30%" />
        </asp:BoundField>
    </Columns>
</asp:GridView>

適合響應式版面,欄寬隨 GridView 總寬度比例分配。

技巧三:RowDataBound 動態設定行高 (解決 Height 固定導致空白)

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowDataBound="GridView1_RowDataBound">
    <Columns>
        <asp:BoundField DataField="content" HeaderText="內容" ItemStyle-Width="400px" />
    </Columns>
</asp:GridView>

// Code-behind
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        // 固定行高 43px,內容超出以省略號顯示 (需配合 CSS table-layout:fixed)
        e.Row.Attributes["style"] = "height:43px;"; 
    }
}

技巧四:TemplateField 完全控制 (最彈性)

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CssClass="fixed-grid">
    <Columns>
        <asp:TemplateField HeaderText="標題" HeaderStyle-Width="300px">
            <ItemTemplate>
                <div class="cell-content">
                    <%# Eval("title") %>
                </div>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="操作" HeaderStyle-Width="100px">
            <ItemTemplate>
                <asp:LinkButton CommandName="Edit" CommandArgument='<%# Eval("id") %>' Text="編輯" />
                <asp:LinkButton CommandName="Delete" CommandArgument='<%# Eval("id") %>' Text="刪除" OnClientClick="return confirm('確定刪除?');" />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

<style>
.fixed-grid { table-layout: fixed; width: 100%; }
.cell-content { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; padding: 5px; }
</style>

自動產生欄位 (AutoGenerateColumns=True) 如何固定寬度?

無法直接設定,需在 `RowDataBound` 中動態指派:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.Header || e.Row.RowType == DataControlRowType.DataRow)
    {
        e.Row.Cells[0].Width = Unit.Pixel(50);   // ID
        e.Row.Cells[1].Width = Unit.Percentage(40); // Title
        e.Row.Cells[2].Width = Unit.Pixel(120);  // Date
        // ...
    }
}

但**強烈建議改用 `AutoGenerateColumns="False"` 明確定義欄位**,可維護性、效能、樣式控制皆優。

綜合最佳實務範本

<asp:GridView ID="gvList" runat="server" 
    AutoGenerateColumns="False" 
    CssClass="grid-fixed"
    GridLines="None"
    ShowHeaderWhenEmpty="True"
    EmptyDataText="無資料">
    
    <Columns>
        <asp:BoundField DataField="id" HeaderText="ID" 
            ItemStyle-Width="60px" ItemStyle-CssClass="text-center" />
        <asp:BoundField DataField="title" HeaderText="標題" 
            ItemStyle-Width="40%" ItemStyle-CssClass="ellipsis" />
        <asp:BoundField DataField="category" HeaderText="分類" 
            ItemStyle-Width="15%" />
        <asp:BoundField DataField="created" HeaderText="建立時間" 
            ItemStyle-Width="150px" DataFormatString="{0:yyyy/MM/dd}" />
        <asp:TemplateField HeaderText="操作" ItemStyle-Width="120px" ItemStyle-CssClass="text-center">
            <ItemTemplate>
                <asp:HyperLink NavigateUrl='<%# "Edit.aspx?id=" + Eval("id") %>' Text="編輯" /> | 
                <asp:LinkButton CommandName="Delete" CommandArgument='<%# Eval("id") %>' Text="刪除" OnClientClick="return confirm('確認刪除?');" />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
    
    <HeaderStyle CssClass="grid-header" />
    <RowStyle CssClass="grid-row" />
    <AlternatingRowStyle CssClass="grid-alt" />
</asp:GridView>

<style>
.grid-fixed { table-layout: fixed; width: 100%; border-collapse: collapse; }
.grid-fixed th, .grid-fixed td { border: 1px solid #ddd; padding: 8px; }
.grid-header { background: #f5f5f5; font-weight: bold; }
.ellipsis { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.text-center { text-align: center; }
</style>

總結選擇指南

需求推薦技巧
快速固定欄寬、溢位省略號技巧一:CSS table-layout:fixed + ItemStyle-Width
響應式百分比欄寬技巧二:HeaderStyle/ItemStyle Width="xx%"
固定行高、多行文本截斷技巧三:RowDataBound 設 height + CSS line-clamp
複雜模板、按鈕、條件顯示技巧四:TemplateField + CSS

掌握 `table-layout: fixed` 核心 CSS 屬性,搭配 `ItemStyle-Width` 與 `TemplateField`,即可徹底掌控 GridView 版面配置。

copyright © 萬盛學電腦網 all rights reserved