The TemplateColumn
Recently, I have been trying to get more and more out of a DataGrid and have found the usual ways to display columns (boundcolumns, hyperlinkcolumns etc) don't have enough. The TemplateColumn has a lot more, it allows you to add much more to your DataGrid. Take the following two examples -
CheckBox / CheckBoxList
A checkbox can be used in a column to show if something is true, yes, available, checked etc. or not. It sometimes looks better than having a 'Yes' or 'No'. You can also use it as a delete checkbox, where a user checks the items that he/she wants deleted and then clicks an update button in the footer.
<asp:templatecolumn> <itemtemplate> <asp:checkbox runat="server" Checked='<%# Container.DataItem("Married") %>' Enabled="False" id="chk1" /> </itemtemplate> </asp:templatecolumn> |
Live Demo |
This will check to see if the person is Married (defined by True or False in the DataSet) and check the box or not. When editing, you can just switch the Enabled to True.
RadioButton / RadioButtonList
I would use these in an edit template. For example -
<asp:templatecolumn> <edittemplate> <asp:radiobuttonList runat="server"> <asp:listitem value="Trek">Star Trek</asp:listitem> <asp:Listitem value="Wars">Star Wars</asp:listitem> </asp:radiobuttonlist> </edittemplate> </asp:templatecolumn> |
Live Demo |
These are just samples of what you can do in TemplateColumns.
When to use TemplateColumns
All of the examples here use template columns to display the data. But remember that there are other kinds of columns, but sadly, they all seem kind of pitiful (when trying to do more than just display and edit data). eg. The Hyperlink column will not allow more than one column of text to be displayed, you have to use a template column -
<asp:templatecolumn> <itemtemplate> <a href=../view.aspx?id=<%# Container.DataItem("ID") %>><%# Container.DataItem("ID") & Container.DataItem("Name") %></a> </itemtemplate> </asp:templatecolumn> |