How to add imageButtons to DataGrid?

G

Guest

I am dynamically creating my datagrid, building each column in real-time via
code-behind (using c#).

The only way i have read to add ImageButtons to my grid dynamically is by
creating a separate template class. However, a class cannot create server
controls (or at least this is beyond me).

I am able to create HTML <INPUT> form elements, however, these are not wired
to my datagrid and hence, when clicked do not fire the datagrid's events
including ItemCommand.

Is there anyway to add imageButtons as web server controls to the datagrid
dynamically?

Thanks,
 
G

Guest

Forgive my last comment: I can add ImageButton's as web server controls via
my template class. However, how do i wire these controls to my datagrid so
that when clicked they fire the ItemCommand event?
 
J

Joe Fallon

Here is a sample that adds 2 image buttons for edit and delete.
The delete is wrapped in a client side confirmation dialog.

Add this to the asp:datagrid section:
OnItemCommand="GetRowInfo"


<ASP:TEMPLATECOLUMN HeaderText="Actions">
<HEADERSTYLE CssClass="DataGridRowTitleCenter"></HEADERSTYLE>
<ITEMSTYLE CssClass="DataGridCellCenter"></ITEMSTYLE>
<ITEMTEMPLATE>
<ASP:IMAGEBUTTON id="btnEdit" runat="server" ToolTip="Edit"
ImageUrl="~/img/edit.gif" CommandName="btnEdit"></ASP:IMAGEBUTTON>
<SPAN onclick="return confirm('Do you really want to delete
this record from the system?')">
<ASP:IMAGEBUTTON id="btnDelete" runat="server"
ToolTip="Delete" ImageUrl="~/img/delete.gif"
CommandName="btnDelete"></ASP:IMAGEBUTTON>
</SPAN>
</ITEMTEMPLATE>
</ASP:TEMPLATECOLUMN>


Then in your code behind create a method with the same name as defined in
OnItemCommand:


Protected Sub GetRowInfo(ByVal source As Object, ByVal e As
DataGridCommandEventArgs)
'Grid paging causes this event to fire and e.Item.ItemIndex=-1 so we
should avoid an error by coding for this case.
If e.Item.ItemIndex >= 0 Then

Dim mIndex As Integer = CType(source, DataGrid).PageSize *
CType(source, DataGrid).CurrentPageIndex + e.Item.ItemIndex

If e.CommandName = "btnDelete" Then
Dim mKey As String = mList(mIndex).code

'after deleting the record, re-load the page.
Response.Redirect("~/Results.aspx")

ElseIf e.CommandName = "btnEdit" Then
'do something here
Response.Redirect("~/Edit.aspx")
End If

End If

End Sub
 

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

Top