如何使用asp.net C#从GridView中获取TemplateField的值?

Dhi*_*esh 2 c# asp.net gridview

我正在尝试检索输入到Gridview文本框中的数据,但是我没有从中获取数据.这是我的代码:

在ASP中

<asp:GridView ID="Add" runat="server">
    <Columns>
         <asp:TemplateField HeaderText="Select" HeaderStyle-Width="100px">
               <ItemTemplate>
                     <asp:CheckBox ID="cbox_Select" runat="server" />
               </ItemTemplate>
         </asp:TemplateField>
         <asp:BoundField DataField = "Name" HeaderText = "Fee Type" />
         <asp:TemplateField HeaderText="Amount" HeaderStyle-Width="100px">
               <ItemTemplate>
                     <asp:TextBox ID="TextBox" runat="server"></asp:TextBox>
               </ItemTemplate>
         </asp:TemplateField>
     </Columns>
</asp:GridView>
Run Code Online (Sandbox Code Playgroud)

在C#中,

for (int i = 0; i< n;i++)
{
      string a = ((TextBox)Add.Rows[i].Cells[2].FindControl("TextBox")).Text;
}
Run Code Online (Sandbox Code Playgroud)

谁能帮我这个?

Win*_*Win 5

您想循环遍历GridViewRowCollection,并找到该控件.

foreach (GridViewRow row in Add.Rows)
{
    var textbox = row.FindControl("TextBox") as TextBox;
    var a = textbox.Text;
}
Run Code Online (Sandbox Code Playgroud)

演示

<asp:Button ID="Button1" runat="server" Text="SubmitButton" 
    OnClick="SubmitButton_Click" />
<asp:GridView ID="Add" runat="server">
    <Columns>
        <asp:TemplateField HeaderText="Amount" HeaderStyle-Width="100px">
            <ItemTemplate>
                <asp:TextBox ID="TextBox" runat="server"></asp:TextBox>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

public class SampleClass
{
    public int Id { get; set; }
    public string Text { get; set; }
}

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        Add.DataSource = new List<SampleClass>()
        {
            new SampleClass {Id = 1, Text = "One"},
            new SampleClass {Id = 2, Text = "Two"},
        };
        Add.DataBind();
    }
}

protected void SubmitButton_Click(object sender, EventArgs e)
{
    foreach (GridViewRow row in Add.Rows)
    {
        var textbox = row.FindControl("TextBox") as TextBox;
        var a = textbox.Text;
    }
}
Run Code Online (Sandbox Code Playgroud)