Write input button in ASP.NET c#

Asked

Viewed 2,084 times

3

I have the following code:

r.Write("<th colspan='3' style='text-align:center'><input id='btEmail_" + (n - 1) + "' name='btEmail_" + (n - 1) + "' runat='server' class='btn bg-brownCinc' onclick='btEmail_' type='button' value='Update' /></th>");

that is inside cycle while drawing an undetermined number of buttons (5, 10 or 15 buttons). And I have:

protected void btEmail_Click(object sender, System.EventArgs e)
{
    Response.Redirect("Index.aspx");
}

When I try to click one of the many buttons generated nothing happens, that is to say the index page is not opened. What is wrong with this code?

2 answers

2

Onclick event of the button element is Clientevent, IE, will look for a Javascript function

What you need is to invoke the server method, fortunately this can be done easily using the Onserverclick attribute (without forgetting the runat=Server)

<input type="button" ID="Button1" runat="server" value="Cliqur Aqui" onServerClick="Button1_Click" />        

This will fire on the event server protected void Button1_click(Object Sender, Eventargs and)

You may notice that the button above will be rendered as

<input onclick="__doPostBack('ctl00$MainContent$Button1','')" name="ctl00$MainContent$Button1" type="button" id="MainContent_Button1" value="Cliqur Aqui" />

Note that there is no onclick ai.

Just one more Gift: You don’t need an event for every button! Use the same event for all buttons and change the ID of each one.

<input type="button" ID="Botao_1" runat="server" value="Cliqur Aqui" onServerClick="Button1_Click" />
<input type="button" ID="Botao_2" runat="server" value="Cliqur Aqui" onServerClick="Button1_Click" />

On Server:

    protected void Button1_Click(object sender, EventArgs e)
    {
        Response.Write((sender as HtmlInputButton).ID);
    }

This will print "Boot 1" or "Boot 2" depending on which one was clicked.

1


The correct thing in this case is to create the element programmatically, using the objects, not to mount the string with the content that has to be rendered.

To create the element to be rendered do so:

protected void Page_Load(object sender, EventArgs args)
{
    if (!IsPostBack) {
        // criando elemento
        Button btnEnviar = new Button();
        btnEnviar.Text = "Texto do elemento";
        btnEnviar.CssClass = "btn btn-brownCinc";
        btnEnviar.Click += AcaoAoClicarNoBotao;

        // adiciona o elemento onde deve ser exibido
        // neste caso, para exemplo, estarei adicionando em um Panel
        Panel1.Controls.Add(btnEnviar);
    }
}

And then just create the event that the button will run. Example:

protected void AcaoAoClicarNoBotao(object sender, EventArgs e)
{
    // ação que será executada
}

Browser other questions tagged

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