什么是最好的WebControl来创建它

时间:2010-05-19 10:02:54

标签: c# asp.net gridview templatefield reusability

当前输出

alt text http://www.balexandre.com/temp/2010-05-19_1159.png

想要输出

alt text http://www.balexandre.com/temp/2010-05-19_1158.png

当前代码

public partial class test : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
            populateData();
    }

    private void populateData()
    {
        List<temp> ls = new List<temp>();

        ls.Add(new temp { a = "AAA", b = "aa", c = "a", dt = DateTime.Now });
        ls.Add(new temp { a = "BBB", b = "bb", c = "b", dt = DateTime.Now });
        ls.Add(new temp { a = "CCC", b = "cc", c = "c", dt = DateTime.Now.AddDays(1) });
        ls.Add(new temp { a = "DDD", b = "dd", c = "d", dt = DateTime.Now.AddDays(1) });
        ls.Add(new temp { a = "EEE", b = "ee", c = "e", dt = DateTime.Now.AddDays(2) });
        ls.Add(new temp { a = "FFF", b = "ff", c = "f", dt = DateTime.Now.AddDays(2) });


        TemplateField tc = (TemplateField)gv.Columns[0];  // <-- want to assign here just day
        gv.Columns.Add(tc); // <-- want to assign here just day + 1
        gv.Columns.Add(tc); // <-- want to assign here just day + 2

        gv.DataSource = ls; 
        gv.DataBind(); 
    }
}

public class temp
{
    public temp() { }

    public string a { get; set; }
    public string b { get; set; }
    public string c { get; set; }
    public DateTime dt { get; set; }
}

和HTML

<asp:GridView ID="gv" runat="server" AutoGenerateColumns="false">
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:Label ID="Label1" runat="server" Text='<%# Eval("a") %>' Font-Bold="true" /><br />
                <asp:Label ID="Label2" runat="server" Text='<%# Eval("b") %>' Font-Italic="true" /><br />
                <asp:Label ID="Label3" runat="server" Text='<%# Eval("dt") %>' />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

我要避免的是重复代码,所以我只能使用一个唯一的TemplateField

我可以用3 x GridView来实现这一点,每天一个,但我真的想简化代码,因为Grid将完全相同(就像HTML代码那样),只是DataSource更改

非常感谢任何帮助,谢谢。

2 个答案:

答案 0 :(得分:0)

使用 ListView

答案 1 :(得分:0)

您可以创建自定义模板并提供该模板三次,如:http://msdn.microsoft.com/en-us/library/aa289501%28VS.71%29.aspx