Dailycode.info

Short solution for short problems

ASP.Net GridView: databinding a subobject

I have a gridview on my page. I want to show information in it that I retrieve from the database. After I get the data via webservices from the database, I map them with process layer object classes. The object classes from the process layer have following structure:

 
public class TESTStock
    {
        private string _guid;
 
        public string Guid
        {
            get { return _guid; }
            set { _guid = value; }
        }
       
 
        private TESTStockLocation _stockLocation;
 
        public TESTStockLocation StockLocation
        {
            get { return _ stockLocation; }
            set { this._ stockLocation = value; }
        }
    }

The subclass looks like this:


public class TESTStockLocation
    {
        private string _guid;
 
        public string Guid
        {
            get { return _guid; }
            set { _guid = value; }
        }
       
        private string _description;
 
        public string Description
        {
            get { return _ description; }
            set { _ description = value; }
        }
 
    }
 

If I want to show the information about the TestStockLocation (the subclass) in my gridview, I will have to use template columns:

<asp:TemplateField HeaderText="Stock location description">
  <ItemTemplate>
   <asp:Label ID="lblCRCID" runat="server"
    Text='<%# ((Namespace.TestStock)(Container.DataItem)).StockLocation.Description %>'>
   </asp:Label>
  </ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Description" HeaderText="Stock descrioption" />
 

Notice that I used Namespace.TestStock, if the object class is in a different namespace, you will have to refer the namespace, even when you have a using clause of this namespace in your code behind.

Now when I databind a list of TestStock items, the description on the subitem teststocklocation will be shown in  template column.

  List<TestStock> mainstockItems = new List< TestStock >();
        Stock st = new Stock();
        mainstockItems = st.GetTestStock();
        this.GridView1.DataSource = mainstockItems;
        this.GridView1.Visible = true;
        this.GridView1.DataBind();