How is Container.DataItem used?

Container.DataItem is a property in ASP.NET used to retrieve and display the data item of a data-bound control.

It is commonly used in templates for data-bound controls such as GridView, Repeater, DataList, etc. In the template, <%# Container.DataItem %> can be used to reference the data item bound to the current row.

In a template, you can display data by using Container.DataItem to access the properties or methods of the data item. For example, you can use <%# Container.DataItem.FieldName %> to display the value of a specific field of the data item.

Here is an example demonstrating how to use Container.DataItem in a GridView template to display data.

<asp:GridView runat="server" ID="GridView1" AutoGenerateColumns="False">
    <Columns>
        <asp:BoundField DataField="ProductName" HeaderText="Product Name" />
        <asp:BoundField DataField="Price" HeaderText="Price" />
        <asp:TemplateField HeaderText="Image">
            <ItemTemplate>
                <img src="<%# Container.DataItem.ImageUrl %>" alt="Product Image" />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

In the example above, Container.DataItem.ImageUrl is used to display the value of the ImageUrl field in the data item.

bannerAds