How to Replace Text in ASP.net GridView« View all ASP.net articles
November 25, 2006
Use the RowDataBound property of the GridView. In the properties window click on the Events button and than select RowDataBound.

Determine wich column you want to replace the text in. Rember to start counting with 0. So column 2 is actually 1.
In this example we will replace the 2nd column's text in the GridView if it contains the word "ASP" and replace it with the word "NET"
Protected Sub GridView1_RowDataBound(ByVal sender As Object,
ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs)
Handles GridView1.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
If e.Row.Cells(1).Text = "ASP" Then
e.Row.Cells(1).Text = "NET"
End If
End If
End Sub
You can also replace one column's text based on another column.
In this example we will replace the contents of the 3rd column in the GridView based on the first column. We will again replace the word "ASP" with the word "NET"
Note that to test the 1st row, we are using: e.Row.Cells(0).Text and to replace the 3rd row, we are using e.Row.Cells(2).Text
Protected Sub GridView1_RowDataBound(ByVal sender As Object,
ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs)
Handles GridView1.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
If e.Row.Cells(0).Text = "ASP" Then
e.Row.Cells(2).Text = "NET"
End If
End If
End Sub
Advanced example: Add an additional word to the existing GridView Column
If the the column contains "NET" we will add "ASP" to it.
Protected Sub GridView1_RowDataBound(ByVal sender As Object,
ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs)
Handles GridView1.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
If e.Row.Cells(0).Text = "NET" Then
e.Row.Cells(0).Text = "ASP" & e.Row.Cells(0).Text
End If
End If
End Sub
Advanced example: Add a hyphen to into the existing GridView Column
If the the column contains "100101" or "101102" we will add a hyphen after the 3rd character. You can substitute the hypen with any other character.
Protected Sub GridView1_RowDataBound(ByVal sender As Object,
ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs)
Handles GridView1.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
If e.Row.Cells(1).Text = "100101" Or e.Row.Cells(1).Text = "102104" Then
e.Row.Cells(1).Text = String.Format("{0}-{1}" _
Left(e.Row.Cells(1).Text, 3), _
Right(e.Row.Cells(1).Text, 3))
End If
End If
End Sub
|