【问题标题】:How to access a textbox text from gridview to a button Onclick event如何从gridview访问文本框文本到按钮Onclick事件
【发布时间】:2013-10-27 16:54:38
【问题描述】:

我在 gridview 中有文本框和按钮。我想要的是,当我单击这些按钮时,文本框中的相应值会更新为数据库,因此我需要访问 OnClick 事件中的文本框文本。我该怎么做?

网格视图:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
            BackColor="#CCCCCC" BorderColor="#999999" 
            BorderStyle="Solid" BorderWidth="3px" CellPadding="4" CellSpacing="2" 
            ForeColor="Black" OnRowDataBound="GridView1_RowDataBound" 
            onselectedindexchanged="GridView1_SelectedIndexChanged">
            <Columns>
                <asp:TemplateField HeaderText="Save 1">
                    <ItemTemplate>
                        <asp:TextBox ID="TextBox1" Width="30px" runat="server"></asp:TextBox>
                        <asp:Button ID="btnSave1" runat="server" Text="Save"  OnClick="btnSave1_Click" />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Save 2">
                    <ItemTemplate>
                        <asp:TextBox ID="TextBox2" Width="30px" runat="server"></asp:TextBox>
                        <asp:Button ID="btnSave2" runat="server" Text="Save"  OnClick="btnSave2_Click" />
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
</asp:GridView>

按钮点击事件:

protected void btnSave1_Click(object sender, EventArgs e)
    {
         //I want to access TextBox1 here.
    }

请帮我解决这个问题。

【问题讨论】:

标签: c# asp.net button gridview


【解决方案1】:

你可以这样做:

protected void btnSave1_Click(object sender, EventArgs e)
{
     GridViewRow row = (GridViewRow)((Button)sender).NamingContainer;
     TextBox TextBox1 = row.FindControl("TextBox1") as TextBox; 

      //Access TextBox1 here.
      string myString = TextBox1.Text;
}

【讨论】:

  • 虽然它正在工作,但文本框值将变为空。为什么?
【解决方案2】:

基本上这是一个如何获取 TextBox 值的示例:

string CustomerID = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtCustomerID")).Text;

【讨论】:

  • 但是由于我的按钮点击事件在gridview之外,e.RowIndex将不起作用。
  • 点击事件触发更新命令。我为您提供的网站将为您提供详细信息。它非常接近你想要的
  • 在站点示例中,他们使用的是FooterTemplate,你能告诉我应该在哪里使用它吗?
  • 虽然它正在工作,但我必须为此创建我不想要的页脚。你有其他方法吗?
  • 检查 DeleteCustomer 函数以及 Gridview 模板。他传递了一个带有他想要删除的值的命令参数?从您的示例中,我看不到任何数据源。如果您不需要呈现数据库中的数据而只保存新记录,则可以使用简单的 HTML5 表格
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-11-14
  • 1970-01-01
  • 1970-01-01
  • 2017-11-23
  • 1970-01-01
  • 1970-01-01
  • 2020-07-08
相关资源
最近更新 更多