You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ASP.NET GridView中实现多行列横向展示商品

解决ASP.NET GridView横向展示商品的问题

你的代码里已经设置了RepeatColumns="4"和RepeatDirection="Horizontal",但还是纵向排列,核心问题出在这几点:

  • 空间限制过严:GridView的Width="310px"根本放不下4个商品(单个商品图片就有278px宽),Height="293px"也小于单个商品的高度(图片就279px),空间不足只能纵向堆叠。
  • 表格样式冲突:CssClass="table table-hover"是Bootstrap标准表格样式,会强制GridView以行-列的表格结构渲染,和横向多列布局逻辑冲突。

修改后的代码

<asp:GridView ID="gvUsers" runat="server" AutoGenerateColumns="False"
    ShowFooter="True"
    ShowHeaderWhenEmpty="True" RepeatRows="3"
    RepeatColumns="4" RepeatDirection="Horizontal"
    OnSelectedIndexChanged="gvUsers_SelectedIndexChanged"
    OnRowDataBound="gvUsers_OnRowDataBound">
    <Columns>
        <asp:TemplateField Visible="true">
            <ItemTemplate>
                <div style="display: inline-block; margin: 10px; text-align: center; width: 280px;">
                    <div style="background-color: #5f98f3; color: white; font-weight: bold; padding: 5px;">
                        <asp:Label runat="server" ID="lblproductid" Visible="false" Text='<%#Eval("ProductID")%>'></asp:Label>
                        <asp:Label ID="Label1" runat="server" Text='<%# Eval("ProductName") %>' 
                            Font-Names="Open Sans Extrabold"></asp:Label>
                    </div>
                    <div style="margin: 5px 0;">
                        <asp:Image ID="Image1" runat="server" BorderColor="#5F98F3" BorderWidth="1px"
                            Height="279px" Width="278px" ImageUrl='<%# Eval("ImagePath","{0}")%>' />
                    </div>
                    <div style="background-color: #5f98f3; color: white; font-weight: bold; padding: 5px;">
                        <asp:Label ID="Label2" runat="server" Text="Price: Rs" Font-Names="Arial"></asp:Label>
                        <asp:Label ID="Label3" runat="server" Text='<%# Eval("ActualPrice") %>' Font-Names="Arial"></asp:Label>
                    </div>
                </div>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

修改说明

  1. 移除了Height、Width和CssClass属性,消除空间限制和样式冲突。
  2. 将ItemTemplate内的table替换为div布局,用display: inline-block实现商品容器横向排列,同时设置固定宽度和间距保证布局整齐。
  3. 保留原有的背景色、字体样式,确保和设计需求一致。
  4. 若坚持使用table结构,也可以保留内部table,但需给table添加display: inline-block样式,同时移除GridView的table类样式。

修改完成后,商品会按照每行4个的规则横向排列,最多显示3行(对应RepeatRows="3"),和你参考的布局效果一致。

内容的提问来源于stack exchange,提问作者Pakistani Underdogs

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 07:36:23