I've been playing lately with DataGrid binding and i wanted to make a button that will open another page and display me something based on an ID (data from database).
The main problem was that i've used
and i searched to add a custom client side click event without using server side event ItemCommand of the datagrid object, with no luck. There was no method of adding and client event handler even if i've used RegisterClientScriptBlock, this worked with only the asp controls that had the onclick event in the attributes list.
I've found another example of using Attributes.Add method of the objects but as i expected i couldnt get to the LinkButton i wanted. Therefor i've tryed my luck with something else and as i suspected it WORKED!
I hope that this little trick can help anybody else in solving most of their problems. This works even with dynamic created elements.
I'll post here some of my working code.
The main problem was that i've used
Code:
<asp:ButtonColumn ButtonType="LinkButton"...>
I've found another example of using Attributes.Add method of the objects but as i expected i couldnt get to the LinkButton i wanted. Therefor i've tryed my luck with something else and as i suspected it WORKED!
I hope that this little trick can help anybody else in solving most of their problems. This works even with dynamic created elements.
I'll post here some of my working code.
Code:
on the aspx file this was the boundcolumn from the datagrid
<asp:ButtonColumn HeaderText="Del" Text="X" ButtonType="LinkButton" CommandName="delete"></asp:ButtonColumn>
on the server side i will show the old and the new method used.
Old method
Private Sub dataGridObject_Click(ByVal sender As Object, ByVal e As DataGridCommandEventArgs) Handles dataGridObject.ItemCommand
Select Case e.CommandName
Case "download"
'myold code which opened an window by using response.write, looking not too good
End Select
End sub
New method
Private Sub dataGridObject_TestSub(ByVal sender As Object, ByVal e As DataGridItemEventArgs) Handles dataGridObject.ItemDataBound
e.Item.Cells(7).Attributes.Add("onclick", "alert(" & e.Item.Cells(5).Text & ");return false;")
End Sub
This solved all my problems.
If i look at the html code generated i'll see this <TD onclick="alert(100);return false;">(it actualy works there) which works and override my default handler created by the server due to the LinkButton. This is what i've wanted all along.
I've used ItemDataBound event cuz i wanted to change the way how the datagrid handles its elements binding. I've placed the ID's returned from database.
I've placed return false at the end of the script code cuz i wanted to cance the refresh of the page(to postback).
This worked on IE, i hope it will work on others script enabled browsers also.
Hope this helps someone in the future.
Good luck and post here your oppinions.