I have noticed a few people looking for ways to easily to certain things with the datagrid, whether that is formating or some other code. There is of course the Item Created event for the datagrid, however this may not be what you are looking for.
Another option is what I will be describing here. Basically you make a function and call that function in the html part of your code.
A simple example would be to format a column from your database so that even if it is null a value is displayed.
Add this function to your code behind page.
[color green]Protected Function FormatColumn(ByVal arg as Object) As String
dim output as String
If arg Is Nothing Then
output = "0"
ElseIf IsDBNull(arg) Then
output = "0"
Else
output = arg
End If
FormatColumn = output
End Function[/color]
Now in the Html view of your page find the datagrid and column you wish to use the function for. Replace the line:[color green] <asp:TextBox id=txtValue runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.DataField") %>'>[/color]
with this one. [color green]<asp:TextBox id=txtValue runat="server" Text='<%# FormatStats(DataBinder.Eval(Container, "DataItem.DataField")) %>'>[/color]
Of course you will need to modify the lines slightly to match what you have. The function itself can be modified to include any conditions that you need.
If you only require some very simple formatting options then the following may be of better use.
If you don't require any complex formatting you may be able to use a built in method. Although I am talking about the datagrid in this FAQ this both of the formatting methods I am using here will work anytime you use databinding in your web form.
Rather than creating your own formatting method here you can instead add a formatting string onto the end of the databinding call. The strings that I have found in VS are as follows:
General - {0}
Dates
---------------------------------
Short Time - {0:t}
Long Time - {0:T}
Short Date - {0:d}
Long Date - {0}
Date & Time - {0:g}
Full Date - {0:G}
The normal databinding syntax as mentioned above looks something like this [color green]
<%# DataBinder.Eval(Container, "DataItem.LastNight") %>[/color]
To add the formatting string just add a comma and put one of the above formatting strings in quotes.
[color green]<%# DataBinder.Eval(Container, "DataItem.LastNight", "{0}") %>[/color]
This would format the incoming data to a long date.
Just remember that whatever data is incoming must be of the proper type to be formatting by the specified string. For example if you have a string incoming don't try to add the "{0:C}" formatting string. The incoming data will not be able to be cast as currency and your application will crash.
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.