Sauron
Sauron

Reputation: 16903

Get Current row from Gridview in ASP.NET

I have a Gridview with delete and edit buttons looks like

<asp:GridView ID="grdTrackedItems" runat="server" AutoGenerateColumns="False" Width="330px"
            BorderStyle="None" OnRowDataBound="OnRowDataBoundTrackedItems" OnRowDeleting="OnRowDeletingTrackedItems">
            <Columns>
              <asp:TemplateField HeaderText="Name">
                <ItemTemplate>
                  <asp:Label ID="lblItem" runat="server" Text='<%# Eval("Item") %>' />
                </ItemTemplate>
              </asp:TemplateField>
              <asp:TemplateField>
                <ItemTemplate>
                  <asp:ImageButton ID="imgDelete" runat="server" ImageUrl="~/Resources/Images/Delete.png"
                    Height="12" Width="12" ToolTip="Delete" CommandName="Delete" />
                </ItemTemplate>
                <ItemStyle Width="22px" />
              </asp:TemplateField>
              <asp:TemplateField>
                <ItemTemplate>
                  <asp:ImageButton ID="imgEdit" runat="server" ImageUrl="~/Resources/Images/Edit.png"
                    Height="12" Width="12" ToolTip="Edit" />
                </ItemTemplate>
                <ItemStyle Width="22px" />
              </asp:TemplateField>
            </Columns>
          </asp:GridView>

I have a text box and Save button on bottom of the page. I want to display the item name in the textbox when I click on the edit button from gridview. How can I do this?

Upvotes: 2

Views: 23220

Answers (3)

womp
womp

Reputation: 116977

Provide a handler for the RowEditing event, and then update your textbox in that handler.

<asp:GridView ID="grdTrackedItems" runat="server" 
             AutoGenerateColumns="False" Width="330px"
            ...
             OnRowEditing="EditRecord">
            <Columns>


protected void EditRecord(object sender, GridViewEditEventArgs e)
{
    Label lbl = (Label)grdTrackedItems.Rows[e.NewEditIndex].Cells[0].FindControl("lblItem");


    MyTextBox.Text = lbl.text;
}

Upvotes: 3

Sauron
Sauron

Reputation: 16903

I got the solution from river-blue's answer.

Add DataKeyNames="Item" to Gridview and inside the edit button click handler

     protected void OnClickEdit( object sender, EventArgs e )
    {
        GridViewRow row = ( (ImageButton) sender ).Parent.Parent as GridViewRow;
        txtName.Text =  grdTrackedItems.DataKeys[row.RowIndex].Value.ToString();
    }

Upvotes: 2

user240709
user240709

Reputation: 207

inside the edit button click handler you can access the current row as below:

protected void Button1_Click1(object sender, EventArgs e)
{
    GridViewRow row = ((ImageButton)sender).Parent.Parent as GridViewRow;
    // Do some thing with this row
}

Upvotes: 3

Related Questions