Tuesday, April 3, 2012

Asp.Net – GridView with TemplateField

The Asp.Net GridView control allows us to bind data from the Data Sources and displays the bound data in a tabular format. The GridView also offers a lot of additional functionality like Paging, Sorting, Formatting, TemplateColumns etc.

Let us now see as to how the GridView control can be used to bind and display data in an Asp.Net page.

Open an Asp.Net page and add a GridView tag with a list of column definitions.



<asp:GridView ID="grdViewOffers" runat="server" Width="400" AutoGenerateColumns="false" HeaderStyle-BackColor="#33CCCC" RowStyle-BackColor="#C9AEC9" RowStyle-HorizontalAlign="Left"> <Columns> <asp:TemplateField HeaderText="Offer ID"> <ItemTemplate>
<asp:Label ID="lblOfferID" runat="server" Text='<%#Eval("OFFER_ID") %>'></asp:Label>
</ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Offer Name"> <ItemTemplate>
<a href="ProjectInfo.aspx?mode=View&OfferID=<%#Eval("OFFER_ID") %>"> <%#Eval("OFFER_NAME") %> </a>
</ItemTemplate> </asp:TemplateField>
<asp:TemplateField HeaderText="Project Description"> <ItemTemplate>
<asp:Label ID="lblProjDesc" runat="server" Text='<%#Eval("PROJECT_DESC") %>'> </asp:Label>
</ItemTemplate> </asp:TemplateField> </Columns>
</asp:GridView>

Once we define the columns in the .aspx page, we shall now bind the data to the data grid with data from the database.
if (!Page.IsPostBack) {
string strQuery = "SELECT OFFER_ID, BUSINESS_OWNER AS OFFER_NAME, PROJECT_DESC FROM Project_Information"; DataSet dsOffers = DataAccessLayer.GetDataSet(strQuery, "dtOffers");

if ((dsOffers.Tables.Count > 0) && (dsOffers.Tables["0"].Rows.Count > 0))
{
grdViewOffers.DataSource = dsOffers.Tables["0"].DefaultView; grdViewOffers.DataBind();
}
else { lblMsg.Text = "No Offers found."; }
}

Once the grdViewOffers.DataBind() method is called, the data is bound to the Grid and is ready to be displayed in the Page.

That's it we have seen how to bind data to a GridView control in Asp.net using TemplateFields


Search Flipkart Products:
Flipkart.com

No comments: