Search code examples
c#asp.netgridviewpostbackfindcontrol

gridview findcontrol returning nothing empty string(Blank)


I am trying to pass a session value from a gridview select row using GridView1_RowEditing1 event. i am able to get session value for primarykey (p.key) but the Associate_ID returns empty.

C# Code behind

protected void GridView1_RowEditing1(object sender, GridViewEditEventArgs e)
    {
       int primarykey =  Convert.ToInt32(GridView1.DataKeys[e.NewEditIndex].Value);
       string name = Convert.ToString(GridView1.Rows[e.NewEditIndex].FindControl("Associate_ID"));
       Session["Number"] = primarykey;
       Session["Name"] = name;
       //redirect
       Response.Redirect("updatee.aspx");
     }

.ASPX

<asp:TemplateField HeaderText="Associate_ID" SortExpression="Associate_ID">
                <EditItemTemplate>
                    <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Associate_ID") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label1" runat="server" Text='<%# Bind("Associate_ID") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>

OUTPUT:

Key: 5

Name:

As you can see i am not getting Associate_ID for selected field. Also tried using

string name = Convert.ToString(GridView1.Rows[3].Cells[3].FindControl("Associate_ID"));

but there was no result, the grid has multiple columns and rows (8*15)

tried suggestions on gridview findcontrol returning empty "" and tried stopping re-binding the GridView on the PostBack. removed DataSourceID from gridview

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ID" OnRowEditing="GridView1_RowEditing1" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">

code behind

     protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //DataSourceID = "SqlDataSource1"
            GridView1.DataSource = SqlDataSource1;
            GridView1.DataBind();
        }
    }

None of this helped. I am still getting a blank value for Associate_ID. i am unable to see where the issue is. Please help!


Solution

  • You are trying to find the Control Associate_ID with FindControl. But it does not exist. Either find TextBox1 or rename the TextBox to Associate_ID.

    <EditItemTemplate>
        <asp:TextBox ID="Associate_ID" runat="server" Text='<%# Bind("Associate_ID") %>'></asp:TextBox>
    </EditItemTemplate>
    
    //or
    
    string name = Convert.ToString(GridView1.Rows[3].Cells[3].FindControl("TextBox1"));
    

    UPDATE

    I see the problem, somehow you are trying to access those control before the edit state has been activated by rebinding the GridView. The edit index has not been set. So place this before the FindControl.

    GridView1.DataSource = yourSource;
    GridView1.EditIndex = e.NewEditIndex;
    GridView1.DataBind();