Write input button in ASP.NET C #

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 within the while loop that draws an indeterminate 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 on one of the many generated buttons nothing happens, ie the index page does not open. What is wrong with this code?

    
asked by anonymous 19.06.2015 / 12:39

2 answers

1

The correct thing here is to create the element programmatically, using the objects, not to assemble the string with the content that will have to be rendered.

To create the element to render, do the following:

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 execute. Example:

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

OnClick event of the button element is ClientEvent, that is, it will look for a Javascript function

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

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

This will trigger the protected void Button1_Click event (object sender, EventArgs e) event

You may notice that the above button will be rendered as

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

Note that onclick does not appear there.

Just one more detail: You do not need an event for each button! Use the same event for all buttons and change the ID of each.

<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" />

No Server:

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

This will print "Botao_1" or "Botao_2" depending on which one was clicked.

    
19.06.2015 / 14:34