петък, 21 януари 2011 г.

Bind DataTable To GridView using TemplateFields ASP.NET

You have a DataTable object with data filled from your database. There is a "how to" here

In the *.aspx page:
<asp:GridView id="gViewSample"  runat="server">
<Columns>
<asp:TemplateField  ItemStyle-CssClass="GridItemClass">
<ItemTemplate>
<asp:Button ID="btnItem" runat="server" Text='<%# Eval("Item_id") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField  ItemStyle-CssClass="GridItemClassDescription">
<ItemTemplate>
<asp:Label ID="lblItemDescription" runat="server" Text='<%# GetItemDescription(Container.DataItem) %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

In the Code behind (C#)
protected string GetItemDescription(object dataItem)
{
    strint itemDescription = DataBinder.Eval(dataItem, "Description").ToString();
    // here is where you do some manipulation with the field data.
    return itemDescription;
}

In your *.css file you put styles for the header/item/footer templates
.Griditemclass
{
width: 70px;
color: Black;
/* etc. etc. */
}

The binding itself:
protected void Page_Load(object sender, EventArgs e)
{
    gViewSample.DataSource = dt;
    gViewSample.DataBind();
}
--------------------------------------------
The Template fields: you can get data there either directly from the DataTable using Eval("FieldName") either by function in the code behind (like GetItemDescription) if you need to manipulate your data. You put your css classes in an external file.

Няма коментари:

Публикуване на коментар