user3065219
user3065219

Reputation: 45

Selected Index of GridView has the value -1 on button click

I have a GridView with an ImageButton on each row. I want to get value from a template field on clicking the button. I have used SelectedIndex in the button_click.

But the SelectedIndex is always -1.

The code I have tried is below.

   protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
   {
       int i = GridView1.SelectedIndex;
       Label t = (Label)GridView1.Rows[i].Cells[0].FindControl("Label1");
       Session["course"] = t.Text;
       Response.Redirect("registration.aspx");
   }

Upvotes: 1

Views: 2001

Answers (2)

Raghurocks
Raghurocks

Reputation: 925

In that case you can go to row command where you can have click event of the image button.

Grid View Row command

Hope this helps.

Upvotes: 1

Vignesh Kumar A
Vignesh Kumar A

Reputation: 28413

you won't get SelectedIndex in ButtonCLick event

so try like this

protected void imgbtn_Click(object sender, EventArgs e)
{
    try {
        // Get the button that raised the event
        LinkButton lnkbtn = (LinkButton)sender;
        // Get the row that contains this button
        GridViewRow gvRow = (GridViewRow)lnkbtn.NamingContainer;
        // Get rowindex
       int i = gvRow.RowIndex;
       Label t = (Label)GridView1.Rows[i].Cells[0].FindControl("Label1");
       Session["course"] = t.Text;
       Response.Redirect("registration.aspx");
        }
    } catch (Exception ex) {

    }
}

protected void grdview1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    try {
        if ((e.CommandName == "ImageButton")) {
            // Get RowIndex
            int RowIndex = Convert.ToInt32(e.CommandArgument);
            // Get Row
            GridViewRow gvr = grdPhone.Rows(RowIndex);
        }
    } catch (Exception ex) 
        {

    }
}

ASPX:

In GridView

you need to set CommandName and Argument like this

 <asp:TemplateField ShowHeader="false">
 <ItemTemplate>
   <asp:ImageButton ID="imgbtn" runat="server" OnClick="imgbtn_Click" CausesValidation="false" CommandName="ImageButton" CommandArgument='<%# Container.DataItemIndex %>'>Edit</asp:ImageButton >
   </ItemTemplate>
  </asp:TemplateField>

Upvotes: 0

Related Questions