如何将Control绑定到GridView中的<itemtemplate>?</itemtemplate>

时间:2011-05-26 04:32:43

标签: asp.net webforms

编辑:我的对象定义如下。我将它传递给GridView1。

public class UserTestorViewModel
{
    public string Username {get;set;}
    public string Password {get;set;}
    public Label SuiteName {get;set;}
}

我将GridView绑定到自定义的List<UserTestorViewModel>

this.GridView1.DataSource = utViewModelList;
this.GridView1.DataBind();

在.aspx我有

<asp:TemplateField HeaderText="LoginName">
<ItemTemplate>
<asp:Label ID="LoginName" runat= "server" Text= '<%# ((ViewModels.UserTestorViewModel)Container.DataItem).User.userName %> '></asp:Label>
</ItemTemplate>
</asp:TemplateField> 

这可行,因为ViewModels.UserTestorViewModel.User.userName是字符串,但是

<asp:TemplateField HeaderText="SuiteName">
<ItemTemplate>
<%# ((ViewModels.UserTestorViewModel)Container.DataItem).SuiteName %>
</ItemTemplate>
</asp:TemplateField>

因为ViewModels.UserTestorViewModel.SuiteName是来自System.Web.UI.WebControls

的标签

那么如何将System.Web.UI.WebControls绑定到<ItemTemplate>而不是System.Web.UI.WebControls

的文本

1 个答案:

答案 0 :(得分:2)

您可以在ItemTemplate中放置一个占位符控件,并在GridView的RowCreated事件上将标签控件放到它上面:

    protected void Page_Init(object sender, EventArgs e)
    {
        GridView1.RowCreated += new GridViewRowEventHandler(GridView1_RowCreated);
    }

    void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            var dataItem = (KeyValuePair<int, Label>)e.Row.DataItem;
            var nameLabelPlaceholder = e.Row.FindControl("NameLabelPlaceholder") as PlaceHolder;
            if (nameLabelPlaceholder != null)
            {
                nameLabelPlaceholder.Controls.Add(dataItem.Value);
            }
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            GridView1.DataSource = GetGridViewDataSource();
            GridView1.DataBind();
        }
    }

    private object GetGridViewDataSource()
    {
        return (from item in Enumerable.Range(1, 10)
                select new KeyValuePair<int, Label>(item, new Label() { ID = string.Format("NameLabel_{0}", item), Text = string.Format("Item #{0}", item), ForeColor = System.Drawing.Color.Red }))
                    .ToDictionary(kvp1 => kvp1.Key, kvp2 => kvp2.Value);
    }


    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" DataKeyNames="Key">
        <Columns>
            <asp:BoundField HeaderText="Id" DataField="Key" />
            <asp:TemplateField HeaderText="Name">
                <ItemTemplate>
                    <asp:PlaceHolder runat="server" ID="NameLabelPlaceholder" />
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>