ASP.NET GridView RowCommand TextBox empty

user346443 picture user346443 · Sep 5, 2011 · Viewed 8.5k times · Source

Hi I have a grid view with a textbox in each row that im trying to get the value of in the RowCommand event. The below code works fine for all rows expect the first one. The textbox.text value for the first row in always empty.

<asp:GridView ID="GridView1" runat="server" OnRowCommand="GridView1_OnRowCommand" >
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                 Title <%#  Eval("Title")%>

                 <asp:TextBox ID="TextBoxAddPost" runat="server"></asp:TextBox>

                <asp:LinkButton ID="LinkButtonAddPost" CommandName="AddPost" CommandArgument='<%# Eval("postId") %>' runat="server">Add Post</asp:LinkButton>

            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

Code-behind:

protected void Page_Load(object sender, EventArgs e)
{
    if(IsPostBack)
        bindGridView();
}    

protected void GridView1_OnRowCommand(object sender, GridViewCommandEventArgs e)
{
        if (e.CommandName == "AddPost")
        {
                GridViewRow row = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);

                TextBox textBox = (TextBox)row.FindControl("TextBoxAddPost");

                //Empty for first row but works for all others

                Debug.WriteLine("row: " + row.RowIndex +  ", textBox:" + textBox.Text.Trim());

                 GridView1.DataBind();
        }
}

The above code has been simplified for illustration purposes. Each row actually contains a child gridview, hence why in need the text box in each row. I fear that the binding in the page_load is overwriting the value of the text box, however, without the page_load binding, the rowCommand Event is not fired.

I find i a bit strange the it works fine for all rows except the first.

Answer

Hiral picture Hiral · Jan 3, 2013

For getting data from textbox, You have to set text property first by putting below code.

<asp:TextBox ID="TextBoxAddPost" runat="server" Text='<%# Eval("Title") %>'></asp:TextBox>

It will definitely give value from textbox.

Either way, You can also set datakeynames property of gridview.Click here for datakeynames