Kerzoz
Kerzoz

Reputation: 331

How to refer to which row was selected when i click textbox in gridview?

I have a gridview, inside the gridview is a textbox on templatefield, how do i get the row index of the clicked textbox when i change its value?

<asp:GridView ID="productView" runat="server" BorderWidth="3px" CellPadding="4" CellSpacing="2" AutoGenerateColumns="False" Width="1000px" OnSelectedIndexChanged="productView_SelectedIndexChanged">
        <Columns>
            <asp:TemplateField HeaderText="Sacks">
                <ItemTemplate>
                    <asp:TextBox ID="txtSacks" runat="server" CssClass="form-control" Text ="0" Width="100px" OnTextChanged="txtSacks_TextChanged" AutoPostBack="true"></asp:TextBox>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>

aspx.cs:

protected void txtSacks_TextChanged(object sender, EventArgs e)
{
    //Rowindex of the texbox
}

Upvotes: 0

Views: 280

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460258

You can get the GridViewRow via the NamingContainer property of the TextBox:

protected void txtSacks_TextChanged(object sender, EventArgs e)
{
    TextBox txt = (TextBox) sender;
    GridViewRow row = (GridViewRow) txt.NamingContainer;
    int rowIndex = row.RowIndex;
}

This is better than using txt.Parent.Parent because it still works even with nested controls (f.e. if you want to add the TextBox to a Table or Panel).

Upvotes: 2

Amit Kumar
Amit Kumar

Reputation: 5962

Get it using RowIndex

GridViewRow gvRow = (GridViewRow)(sender as Control).Parent.Parent;

int index = gvRow.RowIndex;

Upvotes: 2

Related Questions