In a Web Page GridView, how do you handle updating the value of some columns before displaying them.
For example, a column of the GridView displays the status of the record.
If the status is 'P', change it to display 'Pass'.
If the status is 'F', change it to display 'Fail'.
There are at least two ways to handle this, maybe more.
First, you can put a subroutine into the code-behind of the page, coded to accept a string character
and return a string value. Then, use an ItemTemplate to define the binding expression for that column
as the return value of your sub call (passing in the Container.DataItem as the parameter). You can see an
example of this in VB here (there is also a C# example linked on that page, too):
http://dotnetjunkies.com/QuickStartv20/util/srcview.aspx?path=~/aspnet/samples/data/DataBind6.src&file=DataBind6_vb.aspx
Or, you can trap the RowDataBound event of the DataGrid, check the RowType property to see if it's a data row,
and refer to the cell and change its Text value according to the value you find already there. Here is an example
from .NET help for RowDataBound event that sets the text to italic tags around the existing value. You could put
IF logic there to check the existing value and set a different value accordingly.
Here is the VB italics sample from RowDataBound help, to point you in the right direction
(NOTE: you have to either set the OnRowDataBound property of the GridView to point to this subroutine or you
have to add a "Handles" clause at the end of the first line that declares the Sub):
Sub CustomersGridView_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
' Display the company name in italics.
e.Row.Cells(1).Text = "<i>" & e.Row.Cells(1).Text & "</i>"
End If
End Sub
Or, third, why not just have the object that your ObjectDataSource is bound to instead do the transformation for you in
the method call you use for SelectCommand, so your select command returns the data just like you need it? I know that
puts data "formatting" into the business object layer, but it's also a solution if you have problems getting
the display layer to behave as you want.
The RowDataBound looks like a good solution if you can count on the column staying in the SAME order --
because you refer to the Cell by position in the cells collection (zero-based). If the column order changes for
some reason, the code will fail. Therefore, the subroutine in the page-behind and a binding expression looks like the safest approach to me.
from a solution provided by David Stevenson in Message #1141576
|