Get Current row from Gridview in ASP.NET

和自甴很熟 提交于 2021-02-16 20:14:16

问题


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?


回答1:


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;
}



回答2:


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
}



回答3:


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();
    }


来源:https://stackoverflow.com/questions/2046960/get-current-row-from-gridview-in-asp-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!