How do I change the headertext of a datagrid column programmatically

R

Ravi Gudlavalleti

Hi,

I have a datagrid to view the results from a database.
I am using autogenerate because the number of columns returned from the
database change.
I would like to change the column headers as the ones returned from the
database have no spaces
(example: need to change "EMP_NAME" to "EMPLOYEE NAME" or just "NAME")

I tried the following command
datagrid.columns(0).headertext = "NAME"
datagrid.columns(1).headertext = "SSN"

but it didnt work. I said index out of range. When I tried to see how many
columns were there in the grid using
command
lable.text = datagrid.columns.count
it returned 0 no matter how many columns I had.

How do I get around this problem? Any suggestions?

Thanks in advance.
 
K

Ken Cox [Microsoft MVP]

Hi Ravi,

The ItemCreated event gives you a chance to change the headers, but you
still need to know the possible data field names.

Give this a try and let us know if it helps?

Ken
Microsoft MVP [ASP.NET]


Private Sub Page_Load _
(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles MyBase.Load
DataGrid1.DataSource = CreateDataSource()
DataGrid1.DataBind()
End Sub

Private Sub DataGrid1_ItemCreated _
(ByVal sender As Object, _
ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) _
Handles DataGrid1.ItemCreated
Dim intItems As Integer
If e.Item.ItemType = ListItemType.Header _
And e.Item.Cells.Count > 0 Then
For intItems = 0 To e.Item.Cells.Count - 1
Select Case e.Item.Cells(intItems).Text
Case "EMP_NAME"
e.Item.Cells(intItems).Text = "Employee Name"
Case "SSN"
e.Item.Cells(intItems).Text = "Social Insurance No."
End Select
Next
End If
End Sub

Function CreateDataSource() As DataTable
Dim dt As New DataTable
Dim dr As DataRow
dt.Columns.Add(New DataColumn _
("IntegerValue", GetType(Int32)))
dt.Columns.Add(New DataColumn _
("EMP_NAME", GetType(String)))
dt.Columns.Add(New DataColumn _
("SSN", GetType(String)))
dt.Columns.Add(New DataColumn _
("Boolean", GetType(Boolean)))
Dim i As Integer
For i = 0 To 8
dr = dt.NewRow()
dr(0) = i
dr(1) = "Item " + i.ToString()
dr(2) = (1.23 * (i + 1)).ToString
dr(3) = (i = 4)
dt.Rows.Add(dr)
Next i
Return dt
End Function 'CreateDataSource
 

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,994
Messages
2,570,223
Members
46,814
Latest member
SpicetreeDigital

Latest Threads

Top