I created an example because, the way you are doing right after page reload it will lose all references from the added controls:
Create only 1 TemplateField
and place the component TextBox
with Id 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();
}
On the button ButPesquisar
in his method ButPesquisar_Click
place:
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>";
}
}
}
Upshot:
That is, the data is loaded dynamically, but, the TextBox
within the TemplateField
is fixed.
Recommending
If you can make Gridview formatted, with the DataField
already stipulated with TemplateField
if need be, these dynamic creations bring more problems than solution.
When going through gridview I want to store the value in a list.
– user6018
I need more details... do the following, try setting the Textbox ID property before adding it to the cells, and then just search with Findcontrol for that ID, since the name txtValue is the name of the variable that is holding a reference to the object, but the object itself did not have its ID filled. Besides, in this attempt:
string quantidade = ((TextBox)(GridView1.Rows[i].Cells[j].Controls[1])).Text.ToString();
you are searching for the second control within the cell, is that correct? You have other controls within the cell?– Marciano.Andrade
tried this way: Textbox txtValor = new Textbox(); txtValor.Width = 15; txtValor.ID = "txt" then to read: Textbox myTextBox = (Textbox)(Gridview1.Rows[i].Cells[j].Findcontrol("txt"); a mytextbox da null;
– user6018