Finding the row index in a gridview

MoniMatthews
MoniMatthews used Ask the Experts™
on
I am having trouble getting the rowid for the selected row.
I am using this line to retireve the row information:Dim index As Integer = gvIncrement.SelectedRow.RowIndex() but it is not pulling back what I need.

Usually I would use:Dim id As Integer = gvProjCat.DataKeys(e.RowIndex).Value but I am using GridViewCommandEventArgs instaed of System.Web.UI.WebControls.GridViewUpdateEventArgs so I am not sure how to pull out the selected rowid.
Protected Sub gvIncrement_RowCommand(ByVal sender As Object, ByVal e As GridViewCommandEventArgs)
		' *** Retreive the GridViewRow
 
		' Convert the row index stored in the CommandArgument  property to an Integer.
		'Dim index As Integer = Convert.ToInt32(e.CommandArgument)
		Dim index As Integer = gvIncrement.SelectedRow.RowIndex()
 
 
		' Retrieve the row that contains the button clicked  by the user from the Rows collection.
		Dim row As GridViewRow = gvIncrement.Rows(index)
 
		'Get divnum from gridview
		Dim divnum As Label = gvIncrement.Rows(index).FindControl("ed_lblDivNum")
 
		If e.CommandName = "No" Then
			' *** Get the underlying data item - in this case a DataRow
			Dim increment As String = "N"
			Try
				todb3.updateDivisionStatus_data(Session("budgetcycleid"), divnum.Text, increment, Session("m1id"))
			Catch ex As Exception
				MsgBox(" Error can't update at function ggvIncrement_RowUpdating! " & ex.Message)
			End Try
			gvIncrement.EditIndex = -1
			bindGrid()
		ElseIf e.CommandName = "Yes" Then
			' *** Get the underlying data item - in this case a DataRow
			Dim increment As String = "Y"
			Try
				todb3.updateDivisionStatus_data(Session("budgetcycleid"), divnum.Text, increment, Session("m1id"))
			Catch ex As Exception
				MsgBox(" Error can't update at function ggvIncrement_RowUpdating! " & ex.Message)
			End Try
			gvIncrement.EditIndex = -1
			bindGrid()
		End If

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Top Expert 2013

Commented:
You will have to pass it in CommandArgument
1: In the RowDataBound event FindControl that is raising Event...i.e. say a Button..
2: Set CommandArgument of this Button = e.Row.RowIndes
3: In RowCommand event check the CommandName Attribute and get the CommandArgument

For code check this:
http://www.experts-exchange.com/Programming/Languages/C_Sharp/Q_24582234.html

Commented:
Hello ,

As you are using RowCommand so it may be possible that row is not selected that time.  As per my thinking you want row index of row  for which you click command button.

in row command event

Button btn = sender as Button;
        if (drp != null)
        {
            GridViewRow row = btn.NamingContainer as GridViewRow;
            int i  = row.RowIndex;
            // now access your data over here from row.
        }

Author

Commented:
Can you give me a more little explanation of how to write this out? I tried the link but I am now getting instance errors.
Exploring ASP.NET Core: Fundamentals

Learn to build web apps and services, IoT apps, and mobile backends by covering the fundamentals of ASP.NET Core and  exploring the core foundations for app libraries.

Commented:
put your aspx part of gridview and event in which you want that data.
Top Expert 2013

Commented:
As I said earlier here is what you should be doing:
Example of Yes....but you can adapt it for NO

Protected Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As GridViewCommandEventArgs)
    If e.CommandName = "Yes" Then
        Dim rowIndex As Integer = Convert.ToInt32(e.CommandArgument)
    End If
End Sub
Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
    Dim btnYes As Button = DirectCast(e.Row.FindControl("btnYes"), Button)
    If btnYes IsNot Nothing Then
        btnYes.CommandArgument = e.Row.RowIndex.ToString()
    End If
End Sub

Your button will then look:

 <asp:TemplateField HeaderText="Yes">
<ItemTemplate>
<asp:Button ID="btnYes" runat="server" CausesValidation="false" CommandName="Yes"  Text="Yes" />
</ItemTemplate>
</asp:TemplateField>
Top Expert 2013
Commented:
Anyway here is one more way...to set rowIndex as CommandArgument of a button if you don't want to use RowDataBound Event...
This one is more simple:

 <asp:TemplateField HeaderText="Yes">
<ItemTemplate>
<asp:Button ID="btnYes" runat="server" CausesValidation="false"
CommandArgument = <%# Container.DataItemIndex %>  CommandName="Yes"  Text="Yes" />
</ItemTemplate>
</asp:TemplateField>

Same for NO Button

Worth Reading:
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowcommand.aspx


Author

Commented:
Sami,

I have tired your solution and I am now getting object instance errors.

Commented:
tried my ones or put some aspx so i can visualize .

Author

Commented:
jinal,
Where is drp declared?

Commented:

Button btn = sender as Button;
       if (btn != null)
       {
           GridViewRow row = btn.NamingContainer as GridViewRow;
           int i  = row.RowIndex;
           // now access your data over here from row.
       }

Open in new window

Top Expert 2013

Commented:
Jinal...
Button btn = sender as Button;
btn will always be null because sender is the GridView and not the Button control.

This is what Microsoft has to say:

"To determine the index of the row that raised the event, use the CommandArgument property of the event argument that is passed to the event. The ButtonField class automatically populates the CommandArgument property with the appropriate index value. For other command buttons, you must manually set the CommandArgument property of the command button. For example, you can set the CommandArgument to <%# Container.DataItemIndex %> when the GridView control has no paging enabled."

Ref: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowcommand.aspx

--- MoniMatthews:
So may be you might want to show the line that is throwing the execption or some more info on how you implemented the code I gave.

Commented:

Button btn = e.CommandSource as Button;
       if (btn != null)
       {
           GridViewRow row = btn.NamingContainer as GridViewRow;
           int i  = row.RowIndex;
           // now access your data over here from row.
       }

Open in new window

Commented:
you are using <asp:linkbutton> or simple <asp:button>.

/* for <asp:Button > */
Button btn = e.CommandSource as Button;
       if (btn != null)
       {
           GridViewRow row = btn.NamingContainer as GridViewRow;
           int i  = row.RowIndex;
           // now access your data over here from row.
       }
 
/* for <asp:LinkButton > */
LinkButton btn = e.CommandSource as LinkButton;
       if (btn != null)
       {
           GridViewRow row = btn.NamingContainer as GridViewRow;
           int i  = row.RowIndex;
           // now access your data over here from row.
       }

Open in new window

Author

Commented:
Sami,
Here is my code:

Protected Sub gvIncrement_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvIncrement.RowDataBound
If (e.Row.RowState And DataControlRowState.Edit) > 0 Then
If Not IsDBNull(e.Row.DataItem("IncrementOffOn")) Then
'CType(e.Row.FindControl("ddlIncrement"), DropDownList).SelectedValue = e.Row.DataItem("IncrementOffOn")
Dim btnYes As LinkButton = DirectCast(e.Row.FindControl("imgEdit"), LinkButton)
If btnYes IsNot Nothing Then
btnYes.CommandArgument = e.Row.RowIndex.ToString()
End If
Dim btnNo As LinkButton = DirectCast(e.Row.FindControl("imgEdit1"), LinkButton)
If btnNo IsNot Nothing Then
btnNo.CommandArgument = e.Row.RowIndex.ToString()
End If
End If
End If
End Sub

Protected Sub gvIncrement_RowCommand(ByVal sender As Object, ByVal e As GridViewCommandEventArgs)
If e.CommandName = "Yes" Then
Dim rowIndex As Integer = Convert.ToInt32(e.CommandArgument) Here is the line that errors
'Get divnum from gridview
Dim divnum As Label = gvIncrement.Rows(rowIndex).FindControl("ed_lblDivNum")
' *** Get the underlying data item - in this case a DataRow
Dim increment As String = "Y"
Try
todb3.updateDivisionStatus_data(Session("budgetcycleid"), divnum.Text, increment, Session("m1id"))
Catch ex As Exception
MsgBox(" Error can't update at function ggvIncrement_RowUpdating! " & ex.Message)
End Try
gvIncrement.EditIndex = -1
bindGrid()
ElseIf e.CommandName = "No" Then
Dim rowIndex As Integer = Convert.ToInt32(e.CommandArgument)
' *** Get the underlying data item - in this case a DataRow
'Get divnum from gridview
Dim divnum As Label = gvIncrement.Rows(rowIndex).FindControl("ed_lblDivNum")
Dim increment As String = "N"
Try
todb3.updateDivisionStatus_data(Session("budgetcycleid"), divnum.Text, increment, Session("m1id"))
Catch ex As Exception
MsgBox(" Error can't update at function ggvIncrement_RowUpdating! " & ex.Message)
End Try
gvIncrement.EditIndex = -1
bindGrid()
End If
End Sub
This is the error I am getting:
System.FormatException was unhandled by user code
Message="Input string was not in a correct format."

Author

Commented:
Thank you for your help.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial