Textbox and dynamic C# + ASP.NET button

Asked

Viewed 3,281 times

3

I am feeding a webform with textboxes and buttons from a Repeater, according to the tuples(table people) returned in an SQL query, linking the code to specific attributes within these controls. For textboxes I am using the Hidden attribute, while for buttons I am using the Commandargument attribute in order to use it with the Oncommand method. Now I need the Oncommand method to identify which textbox(Hidden attribute) corresponds to the linked Commandargument so that I can enter the information in my database. Is there any way to do this check or even an easier way to achieve my goal?

My Repeater:

<div class="col-md-6" runat="server">
     <asp:Repeater ID="rptControles" runat="server">
          <ItemTemplate>
               <div class="row">
                    <div class="col-md-12">
                         <div class="form-group">
                              <div id="formulario" class="input-group" runat="server">
                                   <asp:TextBox ID="txtURL" class="form-control" hidden='<%# DataBinder.Eval(Container.DataItem, "pes_codigo") %>' placeholder='<%# DataBinder.Eval(Container.DataItem, "pes_nome") %>' runat="server"></asp:TextBox>
                                   <span class="input-group-btn">
                                        <asp:Button ID="btnValidar" CommandArgument='<%# DataBinder.Eval(Container.DataItem, "pes_codigo") %>' OnCommand="btnValidar_Command" CssClass="btn btn-default" runat="server" Text="Go!" CausesValidation="false" />
                                   </span>
                              </div>
                         </div>
                    </div>
               </div>
          </ItemTemplate>
     </asp:Repeater>
 </div>

Page_load:

protected void Page_Load(object sender, EventArgs e)
{
    populaFormulario(Convert.ToInt32(Session["codigo_evento"]));
}

populaFormulario:

public void populaFormulario(int codigoEvento)
{
    ParticipanteDB parDB = new ParticipanteDB();

    rptControles.DataSource = parDB.SelecionarParticipantes(codigoEvento).Tables[0].DefaultView;
    rptControles.DataBind();
}

btnValidar_Command:

protected void btnValidar_Command(object sender, CommandEventArgs e)
{
    var button = (Button)sender;

    var textbox = (TextBox)button.Parent.FindControl("txtURL");

    TextBox1.Text = e.CommandArgument.ToString() + " - " + textbox.Text;
}

Example of return of textboxes and Buttons:

inserir a descrição da imagem aqui

  • Can you use JS? Because if you can, you then have the opportunity to make the call from a method that validates your function, and can even be asynchronous. Javascript will make it easier to find the textbox you want. But with C# in codebehind it is also possible.

  • Of course, it could be in JS yes, however, I’m still new to JS and I have no idea how to develop a function that satisfies my goal. I could create the function to check the controls that have the same attribute value, but I would not know how to handle the insertion in the database after the recovery of this function, since I perform all the insertion in the button in the codebehind. How would you do that?

1 answer

1

Since your Commandargument has the same value as the Hidden attribute of the textbox, take advantage of and use Commandargument itself, which is sent in Commandeventargs.

EDIT : Since you want the Textbox value for the button, you can then use the Parent property of the Sender (in your case). The Parent will be your div form. Once accessing this div, we use the Findcontrol method to search for a control called txtUrl. Remembering to make the proper Casts, follows below the example :

   using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;

    namespace WebApplication3
    {
        public partial class _Default : Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
#region Só um exemplo
                var tabela = new DataTable();
                tabela.Columns.Add(new DataColumn { ColumnName = "pes_codigo" });
                tabela.Columns.Add(new DataColumn { ColumnName = "pes_nome" });

                tabela.Rows.Add("1", "João");
                tabela.Rows.Add("2", "Paulo");
                tabela.Rows.Add("3", "Pedro");
                tabela.Rows.Add("4", "Mateus");

                rptControles.DataSource = tabela;
                rptControles.DataBind();
#endregion
            }

            protected void btnValidar_Command(object sender, CommandEventArgs e)
            {
                var button = (Button)sender;//Pegamos o botão.

                var textbox = (TextBox)button.Parent.FindControl("txtUrl");//button.Parent é a div id= formulário, logo iremos procurar o textbox txtUrl nessa Div.

                Response.Write(textbox.Text);//Pronto, temos o valor do textbox que você quer.
                Response.Write(e.CommandArgument);//Em e.CommandArgument terá o valor de pes_codigo que vem da tabela pessoas.
            }

        }
    }

Note: I only added one CausesValidation="False" on buttons, to avoid problems with validation.

  • Yeah, so far so good, I can get the figures from Commandargument. The problem is that in btnValidar_Command I need to get exactly the value filled in the Textbox corresponding to this btnValidar, understand? Suppose I have 5 Textboxes, each Textbox of these corresponds to the input of a person in the application and these inputs will be made by clicking on btnValidar. Example: my Textbox is the second, when I fill the second Textbox and click on btnValidar it saves only the information I posted, leaving open to other users.

  • I edited my reply, and includes excerpt to get the value of Textbox filled.

  • I just tested it and it didn’t work. I put some breakpoints to check the execution of btnValidar_Command, but it’s not even fired. Does it have something to do with the life cycle of ASP.NET pages? I edited my question with the methods I created.

  • I disabled the Causesvalidation button, my button was like this : <asp:Button ID="btnValidar" CommandArgument='<%# DataBinder.Eval(Container.DataItem, "pes_codigo") %>' OnCommand="btnValidar_Command" CssClass="btn btn-default" runat="server" Text="Go!" CausesValidation="False" />, although it may be better if you include a Validationgroup in the button for each line.

  • I left my button exactly the same as yours and it still didn’t work. Oncommand is still not firing. I edited the button on the question.

  • How are the events being hooked? In the first line of your aspx file, in the page directives, make sure you have the property AutoEventWireup="true" ?

Show 1 more comment

Browser other questions tagged

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