How to bind a control on page to DataSource directly

A lot of time we have lot of controls on our ASP.Net page that are directly bound to data object for which page is being rendered. For example you may be implementing a page to display some details of a product. All the data that you want to display comes from a database record. You can directly bind all the information on the page directly with the data source using FormView on the page. If you don't intend to edit and update the data, you don't have to specify EditTemplate etc. You can simply have ItemTemplate for FormView and display data in read only format. Following snippet shows how this can be done.


<asp:FormView ID="FormView1" runat="server" CellPadding="4" 
	DataKeyNames="CategoryID" DataSourceID="SqlDataSource3" ForeColor="#333333">
	<FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
	<RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
	<ItemTemplate>
		CategoryID:
		<asp:Label ID="CategoryIDLabel" runat="server" 
			Text='<%# Eval("CategoryID") %>' />
		<br />
		CategoryName:
		<asp:Label ID="CategoryNameLabel" runat="server" 
			Text='<%# Bind("CategoryName") %>' />
		<br />
		Description:
		<asp:Label ID="DescriptionLabel" runat="server" 
			Text='<%# Bind("Description") %>' />
		<br />
 </ItemTemplate>
</asp:FormVi

If you have an image to display, you can add Image control inside template and bind ImageUrl property to one of the columns of the data source that contains url for your image.

comments powered by Disqus

Blog Tags