GridView Get TextBox Value

1

I want to get the value of a textbox of a gridview . This Textbox is created by RowDataBound . In the following form:

TextBox txtValor = new TextBox();
e.Row.Cells[i].Controls.Add(txtValor);

Because gridview is dynamic and you can not use templatefield .

I have tried the following methods:

TextBox textBox = row.Cells[j].FindControl("txtValor") as TextBox;
string quantidade = ((TextBox)(GridView1.Rows[i].Cells[j].Controls[1])).Text.ToString();
    
asked by anonymous 23.06.2014 / 13:07

2 answers

1

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.

    
23.06.2014 / 17:49
0
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)

{

e.NewValues["email"]=((TextBox)((GridView)sender).Rows[e.RowIndex].Cells[0].FindControl("MeuTextBox")).Text;

}

This is in rowupdating !!! otherwise one has to know which line you changed the mail!

But I think the issue in the case of Bind

go in the templatecolumn right click on the textbox and put Bind("Email")

    
22.08.2014 / 19:20