javascript within TEMPLATECOLUMNS

B

Brian Lorraine

I've learned how to add javascript to a web control in .NET using the
".Attributes.Add" method.

example:
MYBUTTON.Attributes.add("onClick", "blablafunction")

I'm having a problem adding javascript to a control that is inside a
TEMPLATE COLUMN of a datagrid. The name of my button is "button1". Because it
is in a template column, you can't just type:

button1.attributes.add........

You also can't go this route

DataGrid.FindControl("button1").Attributes.Add.... because the control item
doesn't have an ATTRIBUTES property.

I tried casting it:

Dim testbutton As Button
testbutton = CType(DataGrid.FindControl("button1"), Button)

But testbutton still doesn't have the ATTRIBUTES property.

I tried having a javascript function fire off when the page loads which
which would add some javascript to the button:

document.getElementById("BUTTONID").onclick = function() { blablabla}

This works when a button has a STATIC ID, but if a control is INSIDE a
templatecolumn, .NET will actually give the ID of this control something
completely different everytime you run it depending upon how much information
is in the datagrid.

I've spent all day trying to figure this out, digging throughMSDN articles,
newsgroups, but can't find anywhere else to look. The only thing I can think
of that SHOULD work is to cast the control to a button, but for some reason
this isn't working. Does anyone know a way I can convert this control using
vb.net which would expose the .attributes tag so I can finally add an onclick
event to this buton?

Any help or links appreciated

A desperate,
B
 
S

Sergey Poberezovskiy

In the DataGrid.ItemDataBound event you can write something similar to the
following:

Dim yourButtonColumnOrdinal As Integer = 1 ' or whatever it is
Dim yourButtonControlOrdinal As Integer = 0 ' or whatever it is
Dim item As DataGridItem = e.Item
Select Case item.Type
Case ListItemType.AlternatingItem, ListItemType.Item,
ListItemType.SelectedItem
With
CType(item.Cells(yourButtonColumnOrdinal).Controls(yourButtonControlOrdinal),
Button)
.Attributes.Add("onclick", "myJavascript")
End With
End Select

If you use HtmlButton, then change the cast to that. And you are right,
genetic Control does not have Attributes collection, but WebControl and
HtmlControl do.

HTH
 

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

No members online now.

Forum statistics

Threads
474,138
Messages
2,570,803
Members
47,348
Latest member
nethues

Latest Threads

Top