5

嗨,我有一个网格视图,每行都有一个文本框,我试图在 RowCommand 事件中获取值。下面的代码适用于除第一行之外的所有行。第一行的 textbox.text 值始终为空。

<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>

代码隐藏:

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();
        }
}

出于说明目的,上面的代码已被简化。每行实际上包含一个子网格视图,因此为什么需要每行中的文本框。我担心 page_load 中的绑定会覆盖文本框的值,但是,如果没有 page_load 绑定,则不会触发 rowCommand 事件。

我觉得有点奇怪,它适用于除第一行之外的所有行。

4

2 回答 2

0

我试过了,它工作正常,GridView1_OnRowCommand 通过单击 LinkBut​​tonAddPost 触发:

 <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();
    }

将您的代码与我的代码进行比较。

于 2013-11-09T11:35:00.703 回答
0

要从文本框中获取数据,您必须首先通过放置以下代码来设置文本属性。

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

它肯定会从文本框中提供价值。

无论哪种方式,您还可以设置 gridview 的 datakeynames 属性。单击此处获取数据键名

于 2013-01-03T06:03:12.120 回答