如何通过不同的类对象将类对象绑定到网格视图中?

时间:2012-05-21 11:23:07

标签: asp.net data-binding gridview exception-handling .net-2.0

我有2个班级:

public class clsShipper 
{
    public string ShipperName { get; set; }
}

public class clsJobInfo 
{
    public long JobID { get; set; }

    public clsShipper oShipper = new clsShipper();
}

我的GridView如下

<asp:GridView ID="dgvJobCostList" runat="server" CellPadding="4" ForeColor="#333333" style="font-family:Verdana;font-size:10px;" AutoGenerateColumns="False" OnSelectedIndexChanged="dgvJobCostList_SelectedIndexChanged">
    <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
    <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
    <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
    <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
    <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
    <EditRowStyle BackColor="#999999" />
    <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:CheckBox ID="chkRowCheck" runat="server" />
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="ID">
            <ItemTemplate>
                <asp:Label ID="lblJobID" runat="server" Text='<%# Bind("JobID") %>' />
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Shipper">
            <ItemTemplate>
            <asp:Label ID="lblShipperName" runat="server" Text='<%# Bind("ShipperName") %>' />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>  

我试图通过JobInfo Class对象绑定Shipper Class的ShipperName属性。我试过下面的

protected void btnSearch_Click(object sender, EventArgs e)
{
    if (oOutputJobInfo.Length < 1)
    {
        lblMessage.Text = "Error : No Data Found";
        lblMessage.Visible = true;
        return;
    }
    else
    {
        dgvJobCostList.DataSource = oOutputJobInfo;
        dgvJobCostList.DataBind();
        dgvJobCostList.Visible = true;
    }
}

但是给出了以下错误

  

DataBinding:'Nucleus.BOL.clsJobInfo'不包含名为'ShipperName'的属性。

1 个答案:

答案 0 :(得分:2)

像这样导入命名空间:

<%@ Import namespace="MyNamespace.ToclsJobInfo" %>

如果不同于clsJobInfo

,您可能需要clsShipper的命名空间

然后你可以演员/ unbox clsJobInfo并使用属性oShipper

<asp:TemplateField HeaderText="Shipper">    
  <ItemTemplate>    
    <asp:Label ID="lblShipperName" runat="server" Text='<%# ((clsJobInfo)Container.DataItem).oShipper.ShipperName %>' />    
  </ItemTemplate>  
</asp:TemplateField>