Dynamic Template in Datagrid using VB.NET

J

John

I have successfully built a datatable and datagrid for a
user-selectable field interface. The user can select the fields they
want, and the controlling table has the data type information. I can
format the dates as I want by using the DataFormatString property of
the BoundColumn. That's because the grid sees the data as a date and
knows what to do with it. Now I want to format a phone number that was
stored as a string from 8005551212 as (800)555-1212 and I want to
format an ID number also stored as a string from 0987654321 to
09-87654-321. The biggest reason is to be able to export to MS Excel,
and if you have ever tried exporting data with leading zeros, and all
numbers, Excel is quite happy to convert it to a number, and drop the
leading zero. That, of course, after it converts it to scientific
notation!!!

I have found reference to templates, but no decent documentation that
shows how to dynamically create them, on the VB side.

Any examples out there?
 
S

Steven Cheng[MSFT]

Hi John,

Welcome to MSDN newsgroup.
From your description, you're developing a dynamic fields datagrid web page
which need to format some string based id or phone number. So you're
wondering how to do this through asp.net datagrid's TemplateColumn and make
it programmatical, yes?

If so , I think we can do it through the following steps:

1. As for formatting string through TemplateColumns, we can define some
helper function to do the formatting work and use thiese functions in the
TEmplateColumns' ItemTemplate, for example:
.............

<asp:TemplateColumn HeaderText="ID">
<ItemTemplate>
<%# FormatID(Container.DataItem(0)) %>
</ItemTemplate>
..................

FormatID function is defined in page as public member function:

Public Function FormatID(ByVal id As String)
Return String.Format("({0}){1}-{2}", id.Substring(0, 3),
id.Substring(3, 3), id.Substring(6, 4))
End Function

we can also make it as a Shared(static) function of a certain helper class

2. To make the above TemplateColumns programmatically, we can define a
Custom Template class implemeting the ITemplate interface. The following
MSDN reference as describing this:

#Creating Templates Programmatically in the DataGrid Control
http://msdn.microsoft.com/library/en-us/vbcon/html/vbtskCreatingTemplatesPro
grammaticallyInDataGridControl.asp?frame=true

Hope helps. Thanks,

Steven Cheng
Microsoft Online Support

Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top