Cannot get index of datagrid row when I click on an image button in template column

I have the following code. I'm trying to get the method moveUp to fire off when a little up arrow is clicked. It works fine as a buttoncolumn because then I can use 
to get the selected row index but how do I get an imagebutton within a template column to do this- it always comes back null at the moment. Btw, my datagrid is bound to an array list so I need the index of the row.
Thanks in advance.
1    <%@ Page Language="vb" %>
2    <%@ Import Namespace="System.Web.Mail" %>
3    <%@ Import Namespace="System.Data" %>
4    <%@ Register TagPrefix="Application" TagName="Previous" src="PreviousEmployEntry.ascx" %>
5    <script runat="server">
7        Dim previousEmployments As ArrayList = New ArrayList()
9        Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
11           If Session("page6") Then
13               previousEmployments = Session("previousEmploy")
14               dgPrevious.DataSource = previousEmployments
15               dgPrevious.DataBind()
16               lblHelper.Visible = False
18            ElseIf Not Page.IsPostBack And Session("page5") Then
20               Session("previousEmploy") = previousEmployments
21               dgPrevious.DataSource = previousEmployments
22               dgPrevious.DataBind()
23               lblHelper.Visible = True
25           Else
27           End If
30       End Sub
32       Sub show_form(ByVal Obj As Object, ByVal E As EventArgs)
34           If (Obj.text = "Add New Employer") Then
35               previousEntry.Visible = True
36           Else
37               previousEntry.Visible = True
38      = True
39               previousEntry.checkGap()
40           End If
43       End Sub
45       Sub dataGrid_Click(ByVal s As Object, ByVal e As DataGridCommandEventArgs)
48           Dim x As Integer = e.Item.ItemIndex
49           lblerror.Text = "hello oo ooo " + x.ToString
50           lblerror.visible = True
52           If e.CommandName = "editdelete" Then
54               editdelete(s, e)
56           ElseIf e.CommandName = "up" Then
58               moveUp(s, e)
60           ElseIf e.CommandName = "down" Then
62               moveDown(s, e)
64           End If
65       End Sub
67       Sub moveDown(ByVal s As Object, ByVal e As DataGridCommandEventArgs)
69           Dim x As Integer = e.Item.ItemIndex
70           lblerror.Text = x.ToString
72           Try
73               Dim oldRecord As PreviousEmployment = previousEmployments.Item(x)
75               previousEmployments.Insert(x + 2, oldRecord)
76               previousEmployments.RemoveAt(x)
77               lblerror.Text = x.ToString + "New Item: (x + 1) " + previousEmployments.Item(x + 1).ToString() + " Old Item: (x - 1) " + previousEmployments.Item(x - 1).ToString()
79           Catch ex As System.ArgumentOutOfRangeException
81           Finally
83               'Response.Redirect("emailform6.aspx")
85           End Try
87       End Sub
89       Sub moveUp(ByVal s As Object, ByVal e As DataGridCommandEventArgs)
91           Dim x As Integer = e.Item.ItemIndex
92           lblerror.Text = "hellooooooooooo " + x.ToString
94           Try
95               Dim oldRecord As PreviousEmployment = previousEmployments.Item(x)
97               previousEmployments.Insert(x - 1, oldRecord)
98               previousEmployments.RemoveAt(x + 1)
99               lblerror.Text = x.ToString + "New Item: (x-1) " + previousEmployments.Item(x - 1).ToString() + " Old Item: (x) " + previousEmployments.Item(x).ToString()
101          Catch ex As System.ArgumentOutOfRangeException
103          Finally
105              Response.Redirect("emailform6.aspx")
107          End Try
109      End Sub
111      Sub editdelete(ByVal s As Object, ByVal e As DataGridCommandEventArgs)
113          Dim x As Integer = e.Item.ItemIndex
115          If previousEmployments.Item(x).Gap() Then
117              Dim pe As PreviousEmployment = previousEmployments.Item(x)
118              previousEmployments.RemoveAt(x)
119              If previousEmployments.Count = 0 Then
121                  Session("page6") = False
123              End If
124              previousEntry.Visible = True
125     = True
126              previousEntry.checkGap()
127              previousEntry.theRecord = pe
131          Else
133              Dim pe As PreviousEmployment = previousEmployments.Item(x)
134              previousEmployments.RemoveAt(x)
136              If previousEmployments.Count = 0 Then
138                  Session("page6") = False
140              End If
141              previousEntry.Visible = True
142              previousEntry.theRecord = pe
143          End If
146      End Sub
149      Sub NextPage_Click(ByVal Obj As Object, ByVal E As EventArgs)
152          Session("page6") = True
153          Response.Redirect("emailform7.aspx")   'Redirect the user            
156      End Sub
158      Protected Sub dgPrevious_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)
160      End Sub
161  </script>
164  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
165  <html xmlns="">
167              <tr>
168                  <td>               
170                     <asp:DataGrid ID="dgPrevious" runat="server" AutoGenerateColumns="False" onItemCommand="datagrid_Click" cssclass="applicationinsettable2" OnSelectedIndexChanged="dgPrevious_SelectedIndexChanged">
171                     <HeaderStyle HorizontalAlign="Center" Font-Size="13px" CssClass="header" />
172                      <Columns>
174                          <asp:TemplateColumn>
175                              <ItemTemplate>
176                                          <asp:ImageButton runat="server" ImageUrl="arrowup.gif" CommandName="up" />
177                              </ItemTemplate>
178                          </asp:TemplateColumn>
179                          <asp:ButtonColumn Text="Down" CommandName="down">
180                              <ItemStyle BorderStyle="None" />
181                          </asp:ButtonColumn>
182                          <asp:BoundColumn DataField="DateFrom" HeaderText="From" >
183                              <ItemStyle Wrap="True" />
184                          </asp:BoundColumn>
185                          <asp:BoundColumn DataField="DateTo" HeaderText="To" >
186                              <ItemStyle Wrap="True" />
187                          </asp:BoundColumn>
188                          <asp:BoundColumn DataField="Employer" HeaderText="Employer" >
189                              <ItemStyle Wrap="True" />
190                          </asp:BoundColumn>
191                          <asp:BoundColumn DataField="Position" HeaderText="Your Position" >
192                              <ItemStyle Wrap="True" />
193                          </asp:BoundColumn>   
194                          <asp:BoundColumn DataField="Salary" HeaderText="Salary" >
195                              <ItemStyle Wrap="True" />
196                          </asp:BoundColumn>
197                          <asp:BoundColumn DataField="Reason" HeaderText="Reason for leaving" >
198                              <ItemStyle Wrap="True" />
199                          </asp:BoundColumn> 
200                          <asp:ButtonColumn Text="Edit/Delete" CommandName="editdelete"></asp:ButtonColumn> 
202                      </Columns>
204                     </asp:DataGrid>
205   </td>
206  </tr>
209    		</table>
214      </form>
216  </body>
217  </html>

12/5/2007 2:53:10 PM 72751 articles. 3 followers. Follow

2 Replies

Similar Articles

[PageSpeed] 21


  Tow options:

1. Add a click event handler for this ImageButton. From sender.Parent.Parent you can get the DataGridItem and thus index is got.

2. Use CommandArgument to pass the index like this:


  In DataGrid's ItemCommand event handler, get the index via:




Allen Chen
Microsoft Online Community Support

Please remember to mark the replies as answers if they help and unmark them if they provide no help.
12/7/2007 5:02:44 AM

Hi freelandera,

try this.

Inside the ItemCommandEvent of the datagrid.


DataGridItem dgr = ((ImageButton)sender).Parent.Parent as DataGridItem;




Please remember to click Mark as Answer on the post that helps you, and to click Unmark as Answer if a marked post does not actually answer your question.
View Blog
12/7/2007 5:20:10 AM

Similar Artilces:

Solution Title: Datagrid Template Column Radio Button (get access to the rb control)
Hi. I have a radio button in a template column of a datagrid. All I need to know is how to get access to this to be able to set the radio button as checked or unchecked (depending on the results of a query). I'm trying this: Dim rbactionneeded As RadioButton = CType(e.Item.FindControl("rbactionneeded"), RadioButton) If ansval = "Y" Then 'result from stored procedure rbactionneeded.Checked = True End if (very simplified). I'm getting an erro...

How to determine the row number when clicking a delete button I added to a template column from a GridView control???
Hello all,I am working using the codebehinde the page with VB.NET 2005 (web application).  I have a gridview where I added a template column, inside that templated column I added a delete button.  I would like to know how could I determine which row number corresponds to the clicked button so I can delete the current record.This is what I have: Protected Sub LinkButtonDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs) Try Dim cmd As SqlCommand Dim objConnection As SqlConnection objConnection = New SqlConnecti...

display different images(for image button) in template column for each row
Hi i have a datagrid with a template column(dynamically created) with imagebutton in it. can anyone tell me how to display different images in this column for each row i could display the same image for the entire column thanks red This depends on the logic for selecting different images. If your image depends on the datasource of the DataGrid Item, then you need to set the image in the databound event of the column. Otherwise ... well, there might be many ways. What criteria do you want to use to select the data. Also, post here code used to define the temlate column (i gu...

using javascript getting value from textbox when edit button is clicked and both controls are present in gridview control
Hi All using javascript I want to get value  from textbox when edit button is clicked and both controls that is texbox and button are present in gridview control .Alok Hi aloksinha83, Please see this post: Thanks,Qin Dian TangMicrosoft Online Community SupportPlease remember to mark the replies as answers if they help and unmark them if they provide no help....

Why is my ATLAS TEMPLATED USER CONTROL getting all instances of this controls methods called? I only want it called for the instance that I click the button from...
I have created a templated user control and it uses ATLAS. So...once the control loads, it then makes an ajax call to populate itself. "server" UpdateMode="Conditional" ID="UpdatePanel1" ChildrenAsTriggers="False" > "TNews1" runat="server"> BNNews(<%# Container.Row["TotalItems"].ToString()%>) <%# Container.Row["NewsID"] %> - "BNP35.aspx?newsId=<%# Container.Row["NewsID"]%>&promoId=<%# TN...

Button clicked
I'm using the following VB code per DW .Net docs to try to get the name of the button I've clicked on in a Win Forms datawindow control. Dim buttonClicked As String buttonClicked = dw_setup.ObjectUnderMouse.Gob.Name.ToString() If buttonClicked = "b_1" Then MsgBox("Button 1 was Clicked!") ElseIf buttonClicked = "b_2" Then MsgBox("Button 2 was clicked!") ElseIf buttonClicked = "b_3" Then MsgBox("Button 3 was clicked!") End If It always returns "DataWindow" instead of the button name. It d...

Button.Click does not get fired from template column
i have used Button in Template Column ,but evet Click does not get fired i use this code :   protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { try { if (e.Row.RowType == DataControlRowType.DataRow) { ImageButton Btn = (ImageButton)e.Row.Cells[8].FindControl("GridviewDeleteImgBtn"); Btn.Click += new ImageClickEventHandler(GridviewDeleteImgBtn_Click); } } catch { ...

Unable to get control values after image button click
Hi, All I have trouble with getting control values after I click a 'save' image button. I am doing a editing data process. I use a textbox to display a record data. After I click the 'save' button I want to get the textbox new data. Code in 'save' button click event: listorder = me.txtListOrder.text The error is I am always getting the old data which I displayed in the textbox but not the data I entered later. When I look at the trace Form Collection it shows the new data I entered later. $ContentPlaceHolder1$txtListorder       456 The strange thing ...

Getting the pixel row and column from a clicked point on image
Hi everyone: I have a tiff image that I need to display to a user. They need to be able to zoom in and scroll around and click on a point, from which I need to determine the row and column of the image pixel that they clicked. Using PB functionality, how can I do this? - I can get the PB units of the clicked point - is there a way to convert these to image pixel row and column? OR If I cannot get the information described above from a PB image window, is there an Active X control that anyone has used that contains the capabilities I need (the freer the better). Thanks for ...

Datagrid: Getting index of row that had check box clicked
Hello, I've got a datagrid which is non-Editable. The datagrid has a template column which has a check box in its ItemTemplate template. The check box has its autopostback=True. In my html, I've set: OnCheckedChanged="chkProcess_CheckedChanged". Now once I click the checkbox, it trips my breakpoint at CheckedChanged in my codebehind. What I now need to do is trap the index of the row where the check box was clicked. I know how to do this with an editable dg. However, I'm stumped now that I'm clicking a control within a datagrid. Any help would be appreciated Thanks, Pardo Couldn't qu...

Problem getting the row index number from a template button
Hi I have an image button, which inside my template field. The problem I am having is with the selected row number or index number. This is what I have managed so far; on my image button I have a command name and argument for the row number and I can get the row number. Also on the image button I have an onclick event. Now on the onclick for the image button, what I want to do is to take the selected row number and use it to grab a value from a cell from the selected row. My code on the onclick event is: Dim row as Gridviewrow = CType(imge.Parent.Parent, Gridviewrow) Dim selectedRow as ...

how to get first column value after clicking edit button in datagrid
 Hi, I have a small problem while working with datagrid. My code looks as follows:public void dgrdList_Command(object s, DataGridCommandEventArgs e){    switch (e.CommandName){        case "edit":                EditForm((int)dgrdList.DataKeys[e.Item.ItemIndex]);            break;        case "delete":           ...

Image Button inside a template column
Hi all,I have been searching for 2 days on how to handle a imagebutton click event inside a template column on a datagrid control. Does anyone know how to do it?i really need help in this.Any links to sample code or possible can write a short code example for me to follow.Thanx in advance. Hi,   two ways   1. Set CommandName property of the ImageButton to something, then handle DataGrid's ItemCommand event which would be raised when ImageButton with a CommandName is clicked. The given command name comes to the method via event arguments (so you can check that it is that speci...

How to get ID of Image Control bound with template column of datalist at runtime
 I have bound Image control to a template column within datalist. The Id of Image control is declared as imgPortfolio and id of datalist is dlImage. Now I want to get the Id of Image control bound with template column of datalist at runtime, which in my case is dlImage_ctl00_imgPortfolio. Can anybody tell me how can I get this id 'dlImage_ctl00_imgPortfolio' . this is the id which you can see after running your web site in the source code. I hope you will understand my point.Also I want to get dlImage_ctl00_imgPortfolio at ItemDataBound event of Datalist.  Thanks Are you...

Web resources about - Cannot get index of datagrid row when I click on an image button in template column -

Want to preview our new DataGrid for Xamarin.Forms?
tl;dr Zumero.DataGrid is a Xamarin.Forms control for displaying data in rows and columns. If you would be interested in testing and previewing ...

Mad King DataGrid
This post is about scrolling in WPF and the egocentric DataGrid control. I’ll give the project background but if all you’re interested in is ...

Stack Overflow
Stack Exchange log in - careers - chat - meta - about - faq Questions Tags Users Badges Unanswered Ask Question Top Questions interesting 295 ...

Microsoft Silverlight - Wikipedia, the free encyclopedia
Microsoft Silverlight is an application framework for writing and running rich Internet applications , with features and purposes similar to ...

Flash Builder Plug-in for SAP Netweaver Gateway - Adobe Labs
Search Navigation Labs Home Wiki Home Technologies Alchemy Blueprint Camera Profiles and DNG Profile Editor Cirrus ColdFusion 10 DNG Codec Fireworks ...

Casaba Security » Products » X5s Testing Tool For Finding XSS Vulnerabilities
Security analysis, consulting, development and testing partners who understand your business strategy.

CodeGuru - Microsoft developers related ideas, articles, tips, tricks, comments, downloads, and so much ...
CodeGuru is where developers can come to share ideas, articles, questions, answers, tips, tricks, comments, downloads, and so much more related ...

Caliburn Micro: WPF, Silverlight, WP7 and WinRT/Metro made easy.
A small, yet powerful framework designed for WPF, Silverlight and WP7. It implements a variety of UI patterns for solving real-world problems. ...

Quick Answers - CodeProject
Questions - Free source code and tutorials for Software developers and Architects.; Updated: 11 Jul 2012 11636: first draft of license proliferation committee report
FYI,the first draft report of the OSI's License Proliferation Committee.To join the OSI's license proliferation discuss email list, send anemail ...

Resources last updated: 11/28/2015 8:05:10 PM