Programmerare, skeptiker, sekulärhumanist, antirasist.
Författare till bok om C64 och senbliven lantis.
Röstar pirat.
2008-12-13
Imagine a database (TestDatabase) with a table. One of the columns in the table is a Short (smallint in SQL Server) called Answer. If the value of that column is 0, you want to present the value “No answer”, if the value is 1, you want to present the value “Yes”. Finally, if the value is 2 you want to present the value “No”.
Let’s start with the problem. To display data from the table, I could create a data source on a web page, and connect it to a GridView control. Perhaps it’s even more easy to just drag a GridView control to the web page, and use the wizard to create a data source. The wizard can be accessed by selecting “New data source” as a the datasource in the task pane of the GridView control. After completing the wizard, the GridView now shows the content of the underlying table. It shows the actual values of the Answer column, that is 0, 1 or 2 instead of “No answer”, “Yes” or “No”.
This is one solution for the problem: Templates!
To convert the Answer column of the GridView to a TemplateField, open the task pane for the GridView control again. It looks different now when the control is connected to a data source. Click Edit Columns to bring up the Fields dialog, in the Selected fields list, highlight the Answer column and click the link labeled “Convert this field into a TemplateField”.
The HTML code for the field has now changed from
<asp:BoundField DataField=”Answer” HeaderText=”Answer” SortExpression=”Answer” />
…to…
<asp:TemplateField HeaderText=”Answer” SortExpression=”Answer”>
<EditItemTemplate>
<asp:TextBox ID=”TextBox1″ runat=”server” Text='<%# Bind(“Answer”) %>’></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID=”Label1″ runat=”server” Text='<%# Bind(“Answer”) %>’></asp:Label>
</ItemTemplate>
</asp:TemplateField>
…and it can no longer be edited using the Fields dialog. How ever, you can now replace the label in the <ItemTemplate> tag with any control you like, a custom one if you like. Now, all you have to do, is to assign the value of the field to the desired property of a custom web control that you have created. And that control can write any replacement value to the result stream depending on the value of the property that is assigned to the control.
This might be the HTML code in <ItemTemplate> tag:
<mySpace:MyControl ID=”Label1″ runat=”server” MyProperty='<%# Bind(“Answer”) %>’></mySpace:MyControl>
Categories: Visual Basic 9
Tags: ASP.NET
Bjud mig på en kopp kaffe (20:-) som tack för bra innehåll!
Leave a Reply