【问题标题】:Using Gridview to display multiple items in cells使用 Gridview 在单元格中显示多个项目
【发布时间】:2016-01-11 20:54:01
【问题描述】:

我想使用 ASP.NET/C# 和 Webforms 构建一个页面,以创建一个基本上显示图像/链接/文本网格的页面。这是需要显示的示例。

 _ _ _ _   _ _ _ _   _ _ _ _   _ _ _ _ 
| |img| | | |img| | | |img| | | |img| |
| |_ _| | | |_ _| | | |_ _| | | |_ _| |
|  txt  | |  txt  | |  txt  | |  txt  |
|_ _ _ _| |_ _ _ _| |_ _ _ _| |_ _ _ _|
 _ _ _ _   _ _ _ _   _ _ _ _   _ _ _ _ 
| |img| | | |img| | | |img| | | |img| |
| |_ _| | | |_ _| | | |_ _| | | |_ _| |
|  txt  | |  txt  | |  txt  | |  txt  |
|_ _ _ _| |_ _ _ _| |_ _ _ _| |_ _ _ _|

最终结果将是一个 4x4 网格。 img 和 txt 字段将链接到该项目的特定页面。最终产品将包含更多内容,但对于这个想法的要点,img 和 txt 字段有效。

我从一张桌子开始,但意识到我想要更好的方式来做这件事。我想要一些更容易分配/创建项目的东西。我想到了一个 Gridview,但认为它不会很好地工作,因为我只看到 gridviews 显示数据库表的内容与它们在数据库表中的完全一样。每个“单元格”都将包含 DB 表的一行。

数据库表如下所示:

内容表

Content_ID  Content_Image  Content_Title  Content_Txt  Content_Link
    1         "item1.jpg"     "Title1"      "Text1"     "LinkText1"
    2         "item2.jpg"     "Title2"      "Text2"     "LinkText2"
    3         "item3.jpg"     "Title3"      "Text3"     "LinkText3"
    4         "item4.jpg"     "Title4"      "Text4"     "LinkText4"

现在我想使用 Gridview,如果可以让它工作的话,我只是不确定它是否可以。如果有人对更容易完成我正在尝试做的事情有更好的建议,我将不胜感激。

【问题讨论】:

  • 为您的图像块创建一个用户控件;创建一个转发器并将此用户控件添加到您的项目模板中;为您的图像块编写一个 CSS 类,以便它在达到特定大小时转到下一行

标签: c# asp.net gridview


【解决方案1】:

假设你有下面这样的 CSS

.pictureEntry { margin: 1px 1px 1px 1px; padding: 2px 2px 2px 2px; float: left; border: solid 1px #cccccc; width: 200px !important; height: 250px; font-size: 10pt; }
.pictureEntry .image { max-height: 150px; max-width: 100px; }

在您的页面上添加文字控件以动态构建 HTML 并将其添加到页面中

<asp:Literal ID="DirectoryItems" runat="server" />

在服务器端,构建您的 HTML。

private void BuildContent(string locationId, string sortBy)
{
    var html = new StringBuilder();

    foreach (var item in items)
        html.Append(GetPartialHtml(item));

    DirectoryItems.Text = html.ToString();
}

private string GetPartialHtml(BL.Model.Person person)
{
    var htmlTemplate = "" + 
        "<div class=\"pictureEntry\">" + 
            "<img src=\"##ImagePath##\" class=\"image\" />" +
            "</div>";

        htmlTemplate = htmlTemplate.Replace("##ImagePath##", "your file path");

        return htmlTemplate;
}

如果您只希望每行有特定的项目数,请将此 Literal 控件包装在另一个 DIV 中,该 DIV 具有允许您的项目数的计算宽度

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-14
    • 1970-01-01
    相关资源
    最近更新 更多