Saturday, November 1, 2008

ASP.NET Custom Controls inside Gridview

The gridview is one of asp.net's most versatile function. Best used if you need to perform operations like create read, updated, remove (CRUD). Datalist would be good for CRUD as well. Simply because its as easy as just clicking around with minimal programming involved. Rule of the thumb is:

CRUD: gridview, datalist
CRUD: detailsview (used really for 1 page paging purpsoe)
CR: listview, repeater

But adding a custom control i.e. placing your own dropdownlist inside a gridview can be tricky. Its not as simple as just binding an object as per normal. The codes are as follows:

<asp:TemplateField>
<HeaderTemplate>Active?</HeaderTemplate>

<ItemTemplate>
<asp:Label id="lblClass" runat="server" Text='<%# returnYesNoValue(DataBinder.Eval(Container,"DataItem.active", "{0}")) %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList id="ddlActive" SelectedValue='<%# Bind("active") %>' runat="server">
<asp:ListItem Value="1">Yes</asp:ListItem>
<asp:ListItem Value="0">No</asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
<HeaderStyle BorderStyle="None" />
<ItemStyle BorderStyle="None" />
</asp:TemplateField>

Steps:
1. Create an objectdatasource and link it with the a query from an XSD datafile.
2. Create a gridview and link it with the objectdatasource
3. Insert bound fileds and then insert the template fields
4. Go into the HTML code and then key in the codes above for the template area
5. As you can see its 'label' for viewmode and 'dropdownlist' for editmode
6. Make sure you bind the records with the value from db, and everything should work automatically.

2 comments:

Amit Panchal said...

such a nice & helpful post.

For more info
http://aspdotnet-programming.blogspot.com/

Nisheeth Pandya said...

Nice one