Search code examples
c#asp.netgridviewfindcontrol

Find Control on RowDataBound-Event returns as NULL/Empty


I am trying to get text value of the selected row from my GridView using FindControl, but the FindControl always returns as NULL.

.ASPX Code:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="CID" DataSourceID="SqlDataSource1" OnRowDataBound="GridView1_RowDataBound">
    <Columns>
        <asp:CommandField ShowSelectButton="True" />
        <asp:BoundField DataField="CID" HeaderText="CID" InsertVisible="False" ReadOnly="True" SortExpression="CID" />
        <asp:BoundField DataField="CountryID" HeaderText="CountryID" SortExpression="CountryID" />
        <asp:TemplateField HeaderText="CountryName" SortExpression="CountryName">
            <EditItemTemplate>
                <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("CountryName") %>'></asp:TextBox>
            </EditItemTemplate>
            <ItemTemplate>
                <asp:Label ID="Label1" runat="server" Text='<%# Bind("CountryName") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

C# Code:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        TextBox txt = e.Row.FindControl("TextBox1") as TextBox;
        string name = txt.Text; // returns as NULL
    }
}

Can anybody point out what I am doing wrong here or is there any other way of doing this? I wanted to get value of the CountryName from the above GridView when select button is clicked.


Solution

  • Thank you both! I was able to get data from "ItemTemplate". But i used a different event this time.

    protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            {
                Label txt = GridView1.SelectedRow.FindControl("Label1") as Label;
                string name = txt.Text;
                Label2.Text = name;
    
                Session["Name"] = name;
                Response.Redirect("check.aspx");
            }
        }