I created an example, because, in the way that you are doing right after the page reload, it will lose all references to the controls added:
Create only 1 TemplateField
and put the TextBox
component with the TxtValor
.
<asp:GridView runat="server" ID="GridDados" ClientIDMode="Static" ViewStateMode="Enabled" ValidateRequestMode="Enabled">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="TxtValor" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="ButPesquisar" runat="server" Text="Pesquisar" OnClick="ButPesquisar_Click" />
<asp:Label Text="" ID="LblResultado" runat="server" />
Loading this GridView:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Grid();
}
}
private void Grid()
{
GridDados.DataSource = (new object[]
{
new { id = 1, nome = "teste 1"},
new { id = 2, nome = "teste 2"}
})
.ToArray();
GridDados.DataBind();
}
No button ButPesquisar
in your method ButPesquisar_Click
put:
protected void ButPesquisar_Click(object sender, EventArgs e)
{
LblResultado.Text = string.Empty;
foreach (GridViewRow item in GridDados.Rows)
{
TextBox txtValor = item.FindControl("TxtValor") as TextBox;
if (txtValor != null && !string.IsNullOrEmpty(txtValor.Text))
{
LblResultado.Text += txtValor.Text;
LblResultado.Text += "<br>";
}
}
}
Result:
That is, the data is loaded dynamically, but, TextBox
within TemplateField
is fixed.
Recommendation
If you can make GridView formatted, with
DataField
already stipulated with
TemplateField
if you need, these dynamic creations bring more problems than solution.