ASP.NET GridView RowCommand TextBox is empty

Hi I have a grid with a text box in each row that is trying to get a value in the RowCommand event. The code below works fine for all lines waiting for the first. The textbox.text value for the first line is 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>

Rear code:

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 is simplified to illustrate. Each row actually contains a child gridview, so this requires a text field in each row. I'm afraid that the binding in page_load will overwrite the value of the text field, however, without the page_load binding, the rowCommand event does not fire.

I find it a little strange that it works fine for all lines except the first.

+5
2

, , .

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

.

datakeynames gridview. datakeynames

0

, , GridView1_OnRowCommand , LinkButtonAddPost:

 <asp:GridView ID="GridView1"  runat="server"  OnRowCommand="GridView1_RowCommand">
            <Columns>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:TextBox ID="TextBoxAddPost" runat="server" Text='<%# Eval("ID") %>'></asp:TextBox>
                        <asp:LinkButton ID="LinkButtonAddPost" CommandName="AddPost" CommandArgument='<%# Eval("ID") %>' runat="server">Add Post</asp:LinkButton>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>

page_load :

 protected void Page_Load(object sender, EventArgs e)
    {
        GridView1.DataSource = Data.RequestPaymentDB.GetRequestPaymentByRequestID(9208060001);
        GridView1.DataBind();
    }

.

0

All Articles