How to get the data typed in the Textbox that was created dynamically?

Asked

Viewed 690 times

2

I created some controls TextBox dynamically in my Code Behind and I need to redeem the values in a new method, but I cannot use the textbox changed in a new method.

        try
        {
            DataTable tbDadosAux =// Método para obter dados;
            DataTable tbDados = //filtra dados

            qtd.Value = tbDados.Rows.Count.ToString();

            table1.HorizontalAlign = HorizontalAlign.Center;
            table1.CssClass = ("table table-bordered table-hover table-striped");


            if (tbDados.Rows.Count !=0)
            {
                 tabela1.Visible = true;
            }

            for (int i = 0; i < tbDados.Rows.Count; i++)
            {

                TableRow linha = new TableRow();
                TableCell c1 = new TableCell();
                TableCell c2 = new TableCell();
                TableCell c3 = new TableCell();

                Label lblPesNm = new Label();
                TextBox txtSeqNum = new TextBox();
                HiddenField hdPesCodComp = new HiddenField();

                c1.Text = tbDados.Rows[i]["RETORNO"].ToString();
                c1.HorizontalAlign = HorizontalAlign.Left;

                txtSeqNum.ID = "txtSeqNum" + (i + 1);
                txtSeqNum.Text = tbDados.Rows[i]["SEQUENCIAL"].ToString();
                c2.Controls.Add(txtSeqNum);
                c2.HorizontalAlign = HorizontalAlign.Left;

                table1.HorizontalAlign = HorizontalAlign.Center;
                table1.CssClass = ("table table-bordered table-hover table-striped");

                linha.Cells.Add(c1);
                linha.Cells.Add(c2);


                table1.Rows.Add(linha);
            }


        }
        catch (Exception ex)
        {
            if (tran.Connection != null)
            {
                tran.Rollback();
                conn.Close();
               // Erro.InnerHtml = "Ocorreu o seguinte erro: " + ex.Message;
            }
        }
        finally
        {
            if (tran.Connection != null)
            {
                tran.Commit();
                conn.Close();
            }
        }
  • 5

    Why can’t you use it? Give more details.

  • I have tried to rescue like this: Textbox text= (Textbox)table1.Findcontrol("txtSeqNum" + 1);

  • 5

    And why doesn’t that work? I still can’t understand what your problem is. Try reading your question as someone who knows nothing about your project and see if you can understand anything.

  • 1

    I already solved it. I gave a request.Form[name].

  • You may even have succeeded with Request.Form, but, lost all page breaking the main link ...

2 answers

0


As reported in your comment with Request.Form you can recover, but it’s not the right way for features like this, use components like Repeater that are lightweight and can bring much more functionality.

The manner employed by you in the question will not succeed, because, you will not be able to persist the die dynamically like this. You know what happens when you press a Submit button, this data will disappear (although not seeing your code is a curricular error), so I decided to create a very simple example.

Example:

Create a Repeater like this inside a page ASPX:

<%@ Page Language="C#" AutoEventWireup="true" 
       CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication3.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:Repeater runat="server" ID="RptDados">
            <HeaderTemplate>
                <table>
                    <tr>
                        <th>Id</th>
                        <th>Nome</th>
                    </tr>
            </HeaderTemplate>
            <ItemTemplate>
                <tr>
                    <td>
                        <asp:HiddenField ID="HId" Value='<%#Eval("Id") %>' runat="server" />
                        <asp:Literal runat="server" Text='<%#Eval("Id") %>'></asp:Literal>
                    </td>
                    <td>
                        <asp:TextBox ID="TNome" runat="server" Text='<%#Eval("Nome") %>'></asp:TextBox>
                    </td>
                </tr>
            </ItemTemplate>
            <FooterTemplate>
                </table>
            </FooterTemplate>
        </asp:Repeater>
        <asp:Button Text="Enviar" runat="server" OnClick="BtnEnviar_Click"  ID="BtnEnviar" />
        <asp:Label Text="" runat="server" ID="LblResposta" />
    </form>
</body>
</html>

Note that in the ItemTemplate i have the fields that will receive the values dynamically, that is, the items will be repeated according to the amount of elements that I will send DataTable and Repeater will take charge of loading the items. After you create in the Button Send it will trigger an event that will load the modifications in this Label Lblresposta. Check this in the code below:

In the code:

using System;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication3
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {                
                Carregar_Repeater();                
            }
        }

        public void Carregar_Repeater()
        {
            DataTable _DataTable = new DataTable();
            _DataTable.Columns.Add("Id", typeof(int));
            _DataTable.Columns.Add("Nome", typeof(string));

            DataRow _Row = null;
            _Row = _DataTable.NewRow();
            _Row["Id"] = 1;
            _Row["Nome"] = "Nome 1";
            _DataTable.Rows.Add(_Row);

            _Row = _DataTable.NewRow();
            _Row["Id"] = 2;
            _Row["Nome"] = "Nome 2";
            _DataTable.Rows.Add(_Row);


            RptDados.DataSource = _DataTable;
            RptDados.DataBind();
        }

        protected void BtnEnviar_Click(object sender, EventArgs e)
        {
            LblResposta.Text = string.Empty;
            foreach (RepeaterItem _Item in RptDados.Items)
            {
                HiddenField HId = _Item.FindControl("HId") as HiddenField;
                TextBox TNome = _Item.FindControl("TNome") as TextBox;

                LblResposta.Text += string.Format("<p>{0} {1}</p>", HId.Value, TNome.Text);
            }
        }
    }
}

In the method Load_repeater I just pass the data to DataSource of Repeater and have the data uploaded (can be any kind of Collection (IList, ICollection, etc, but in your case it was DataTable))

With this example you will be able to understand I believe the process itself ...

0

There is this way that does not scan the Reset and goes straight to the line the user selects.

protected void Button_Atualizar_OnClick(object sender, EventArgs e) 
{
    Control botao = (Control)sender; 
    RepeaterItem item =(RepeaterItem)botao.Parent;

    TextBox txt = (TextBox)item.FindControl("TextBox2");
    string titulo = txt.Text;

    TextBox txt1 = (TextBox)item.FindControl("TextBox3");
    string descricao = txt1.Text;

    Label lbl1 = (Label)item.FindControl("Label33");
    string cod_item = lbl1.Text; 
    ...
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.