如何在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>
修改说明
- 移除了
Height、Width和CssClass属性,消除空间限制和样式冲突。 - 将ItemTemplate内的table替换为div布局,用
display: inline-block实现商品容器横向排列,同时设置固定宽度和间距保证布局整齐。 - 保留原有的背景色、字体样式,确保和设计需求一致。
- 若坚持使用table结构,也可以保留内部table,但需给table添加
display: inline-block样式,同时移除GridView的table类样式。
修改完成后,商品会按照每行4个的规则横向排列,最多显示3行(对应RepeatRows="3"),和你参考的布局效果一致。
内容的提问来源于stack exchange,提问作者Pakistani Underdogs
相关产品推荐
相关产品推荐

