【问题标题】:How do I format the data in ASP.NET如何在 ASP.NET 中格式化数据
【发布时间】:2014-09-30 08:45:51
【问题描述】:

我正在使用 ASP.NET 和 SQL。

我在一个表中有 3 列。我应该以这种方式填充数据:

Date: 2014-09-22
Description1: xyz (this should be bold)
Description2 pqrs (normal paragraph)

在水平标签之后应该出现另一个数据


Date: 2013-09-22 
Description1: abcd (this should be bold)
Description2 qwe (normal paragraph)

我可以在GridView 中填充数据,但我不知道如何以这种方式格式化数据。我是 ASP.NET 的新手。

建议我一些工具或链接,或者请帮助编写代码。

【问题讨论】:

标签: asp.net


【解决方案1】:

在您的 aspx/ascx 中,您需要使用asp:Repeater 控件,如下所示:

    <asp:Repeater runat="server">
        <ItemTemplate>
            <p>Date: <asp:Literal runat="server" ID="litDate"></asp:Literal></p>
            <p>Description 1: <strong><asp:Literal runat="server" ID="litDesc1"></asp:Literal></strong></p>
            <p>Description 2: <asp:Literal runat="server" ID="litDesc2"></asp:Literal></p>
        </ItemTemplate>
        <SeparatorTemplate>
            <hr />
        </SeparatorTemplate>
    </asp:Repeater>

在代码隐藏中,您应该将对象集合绑定到此Repeater,并处理OnDataBinding 事件,您应该为asp:Literal 控件分配适当的值:

class DataItem
{
    public DateTime Date { get; set; }

    public string Desc1 { get; set; }

    public string Desc2 { get; set; }
}

protected void Page_Load(object sender, EventArgs e)
{
    rptData.DataSource = new[]
        {
            new DataItem { Date = new DateTime(2013, 9, 30), Desc1 = "Test Desc 1", Desc2 = "Test Desc 2" },
            new DataItem { Date = new DateTime(2013, 9, 30), Desc1 = "Test Desc 3", Desc2 = "Test Desc 4" } 
        };

    rptData.ItemDataBound += OnItemDataBind;
    rptData.DataBind();
}

protected void OnItemDataBind(object sender, RepeaterItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {
        var data = e.Item.DataItem as DataItem;

        var dateLiteral = e.Item.FindControl("litDate") as Literal;
        dateLiteral.Text = data.Date.ToString("yyyy-MM-dd");

        var desc1Literal = e.Item.FindControl("litDesc1") as Literal;
        desc1Literal.Text = data.Desc1;

        var desc2Literal = e.Item.FindControl("litDesc2") as Literal;
        desc2Literal.Text = data.Desc2;
    }
}

【讨论】:

  • 谢谢...它的作品...正如我所料! ...我像这样修改代码

    Date:

  • 是的,DataBinder.Eval 也可以。我只是更喜欢强类型而不是像DataBinder.Eval 那样将属性名称作为字符串传递。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-14
  • 1970-01-01
相关资源
最近更新 更多