locked
Onclick Event Doesn´t work when writed from Response.Write RRS feed

  • Question

  • User-1163281027 posted

    Hi,

    I am loading content from Database and Writing the code with Response.Write.

     SqlConnection connect = new SqlConnection("Data Source=DESKTOP-RLSGLB6;Initial Catalog=PAP;Persist Security Info=True;User ID=sa;Password=ma01082001");
    
                    try
                    {
                        connect.Open();
                        SqlCommand bilhetes = new SqlCommand("SelectArtigo", connect);
    
    
                        bilhetes.CommandType = CommandType.StoredProcedure;
                        bilhetes.ExecuteNonQuery();
    
    
                        SqlDataReader Lerbilhetes =  bilhetes.ExecuteReader();
                        while (Lerbilhetes.Read())
                        {
                            if (Lerbilhetes.HasRows == true)
                            {
                                Response.Write(" <div class='tick' style='background-color: #fff'>'");
                                Response.Write("<h5>" + Lerbilhetes[3].ToString() + "</h5>");
                                Response.Write("<hr />");
                                Response.Write("<div>");
                                Response.Write("<img src='Imagem\\Eventos\\"+Lerbilhetes[55].ToString()+"' height='120px' width='150px'>");
                                Response.Write("<br />");
                                Response.Write("<label for= 'qtd_tik' >Qtd.</ label >");
                                Response.Write("<input type='number'  min='0' max='10'  name='qtd_tik'  id='qtd_tik'"+ Lerbilhetes[0].ToString() + "'>");
                                //Button
                                Response.Write("<asp:Button runat='server'  OnClick='btn_Venda' class='sell_tik' height='10px' width='100px'>ADD</asp:Button>");
                                //Button
                                Response.Write("<small id='id_item'>" + Lerbilhetes[0].ToString() + "</small>");
                                Response.Write("</div>");
                                Response.Write("</div>");
    
    
                            }
                        }
    
                    }
                    catch (Exception erro)
                    {
                        Response.Write("Erro:" + erro.Message);
                    }

    I have a button that has an Onclick event and when clicked it says :

    Uncaught ReferenceError: btn_Venda is not defined
    at HTMLUnknownElement.onclick

    what should i do ?

    With the best regards,

    Days.galante.

     

    Monday, October 7, 2019 12:38 PM

All replies

  • User475983607 posted

    what should i do ?

    You're not using standard ASP.NET Web Forms programming constructs.  If you take a moment to look at the resulting HTML you'll see the code is located at the top of the page.  The best I can recommend is going through a few Getting Started tutorials to learn the basics.

    https://docs.microsoft.com/en-us/aspnet/web-forms/

    Monday, October 7, 2019 2:02 PM
  • User-719153870 posted

    Hi Days.galante,

    According to your description, it seems you are trying to create html markup and an asp button with an event handler in c#.

    The reason why the button won't work is because this <asp:Button /> is a weboform aspx control, this control will be compiled to html <input type="submit" />, so if you directly write this <asp:Button /> in html with no compile progress, it won't work as you wished.

    If i didn't misunderstanding anything, then you can achieve this requirement with a Literal control and a Placeholder control.

    You can also refer to below demo:

    ASPX:

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                <asp:Literal ID="Literal1" runat="server"></asp:Literal>
                <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
                <asp:Literal ID="Literal2" runat="server"></asp:Literal>
            </div>
        </form>
    </body>
    </html>

    CS:

    protected void Page_Load(object sender, EventArgs e)
            {
                StringBuilder sb = new StringBuilder();
                sb.Append(" <div class='tick' style='background-color: #fff'>");
                sb.Append("<h5>Title</h5>");
                sb.Append("<hr />");
                sb.Append("<div>");
                sb.Append("<img src='Images\\FCF.jpg' height='120px' width='150px'>");
                sb.Append("<br />");
                sb.Append("<label for= 'qtd_tik' >Qtd.</ label >");
                sb.Append("<input type='number'  min='0' max='10'  name='qtd_tik'  id='qtd_tik" + "123" + "'>");
                Literal1.Text = sb.ToString();
                ////Button
                Button btnVenda = new Button();
                btnVenda.Text = "ADD";
                btnVenda.ID = "btn_Venda";
                btnVenda.ControlStyle.CssClass = "sell_tik";
                btnVenda.Width = 100;
                btnVenda.Height = 10;
                btnVenda.Click += new EventHandler(btn_Venda);
                PlaceHolder1.Controls.Add(btnVenda);
                ////Button
                sb.Clear();
                sb.Append("<small id='id_item'>" + "aaa" + "</small>");
                sb.Append("</div>");
                sb.Append("</div>");
                Literal2.Text = sb.ToString();
            }
    
            protected void btn_Venda(object sender, EventArgs e)
            {
                Response.Write("123");
            }

    Here's the result of this demo:

    Hope this could help.

    Best Rgeard,

    Yang Shen

    Tuesday, October 8, 2019 5:45 AM
  • User-1163281027 posted

    Hi Yang,

    I really appreciate your help!

    This method kinda worked. 

    Iam using a cicle do write content , 

     StringBuilder sb = new StringBuilder();
                SqlConnection con = new SqlConnection("Data Source=DESKTOP-RLSGLB6;Initial Catalog=PAP;Persist Security Info=True;User ID=sa;Password=xxxxxxxxx");
                con.Open();
    
    
                SqlCommand Bilhete = new SqlCommand("SELECT * FROM Item where BarCode  LIKE '1%'", con);
                SqlDataReader LerBilhete;
                LerBilhete = Bilhete.ExecuteReader();
    
    
    
    
                while (LerBilhete.Read())
                {
                    if (LerBilhete.HasRows == true)
                    {
    
                        sb.Append(" <div class='tick ' style='background-color: #fff'>'");
                        sb.Append("<h5>" + LerBilhete[3].ToString() + "</h5>");
                        sb.Append("<hr />");
                        sb.Append("<div>");
                        sb.Append("<img src='Imagem\\Eventos\\" + LerBilhete[55].ToString() + "' height='120px' width='150px'>");
                        sb.Append("<br />");
                        sb.Append("<label for= 'qtd_tik' >Qtd.</ label >");
                        sb.Append("<input type='number'  min='0' max='10'  name='qtd_tik'  id='qtd_tik'" + LerBilhete[0].ToString() + "'>");
                        Literal1.Text = sb.ToString();
                        ///Button
                        Button btnVenda = new Button();
                        btnVenda.Text = "ADD";
                        btnVenda.ID = "btn_Venda"+ LerBilhete[0].ToString() +"";
                        btnVenda.ControlStyle.CssClass = "sell_tik";
                        btnVenda.Width = 150;
                        btnVenda.Height = 50;
                        btnVenda.Click += new EventHandler(btn_Venda);
                        PlaceHolder1.Controls.Add(btnVenda);
                        ///Button
                        sb.Append("<small id='id_item' style='visibility: hidden'>" + LerBilhete[0].ToString() + "</small>");
                        sb.Append("</div>");
                        sb.Append("</div>");
    
                        Literal2.Text.ToString();
    
    
    
                    }
                }
    
    
    
                con.Close();

    and it was supposed to appear one button on each Row, but  it appears like this!

    what should i do ?

    Tuesday, October 8, 2019 3:53 PM
  • User-719153870 posted

    Hi Days.galante,

    As @mgebhard said, you will need a data bound control to bind all these dynamic data from your database.

    The strange thing is that why would you want to create all these html markup and asp controls in the back code, this will make your logic quite complex.

    Even though, i will provide a demo which create all the controls in the back, please refer to below code:

    SQL:

    create table Item
    (
    id int identity(1,1),
    title varchar(50),
    [image] varchar(200)
    )
    
    insert into Item values('T1','Images\\FCF.jpg')
    insert into Item values('T2','Images\\FCF2.jpg')
    insert into Item values('T3','Images\\CC.jpg')
    insert into Item values('T4','Images\\FCF2.jpg')
    insert into Item values('T5','Images\\CC.jpg')
    insert into Item values('T6','Images\\FCF.jpg')
    
    select * from Item

    ASPX:

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                <asp:DataList ID="DataList1" runat="server" RepeatColumns="4" RepeatDirection="Horizontal" RepeatLayout="Table" OnItemDataBound="DataList1_ItemDataBound">
                    <ItemTemplate>
                        <asp:Label ID="Label1" runat="server" Text='<%#Eval("id") %>' Visible="false"></asp:Label>
                        <asp:Literal ID="Literal1" runat="server"></asp:Literal>
                        <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
                        <asp:Literal ID="Literal2" runat="server"></asp:Literal>
                    </ItemTemplate>
                </asp:DataList>
            </div>
        </form>
    </body>
    </html>

    CS:

    protected void Page_Load(object sender, EventArgs e)
            {
    //bind your data in page load event SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=DatabaseTestPool;Integrated Security=True"); con.Open(); SqlDataAdapter ad = new SqlDataAdapter("select * from Item", con); DataSet ds = new DataSet(); ad.Fill(ds, "Users"); DataTable dt = ds.Tables[0]; DataList1.DataSource = dt; Session["datatable"] = dt; DataList1.DataBind(); } protected void btn_Venda(object sender, EventArgs e) { Button bt = sender as Button; string id = bt.CommandArgument.ToString(); Response.Write("123"); } protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e) {
    //bind specific row data dynamically in itemdatabound event Label la1 = e.Item.FindControl("Label1") as Label; Literal lit1 = e.Item.FindControl("Literal1") as Literal; Literal lit2 = e.Item.FindControl("Literal2") as Literal; PlaceHolder ph1 = e.Item.FindControl("PlaceHolder1") as PlaceHolder; StringBuilder sb = new StringBuilder(); int id = Convert.ToInt32(la1.Text); DataTable dt = Session["datatable"] as DataTable; DataRow dr = dt.Select("id=" + id.ToString()).FirstOrDefault(); sb.Append(" <div class='tick' style='background-color: #fff'>"); sb.Append("<h5>" + dr.Field<string>("title") + "</h5>"); sb.Append("<hr />"); sb.Append("<div>"); sb.Append("<img src='" + dr.Field<string>("image") + "' height='120px' width='150px'>"); sb.Append("<br />"); sb.Append("<label for= 'qtd_tik' >Qtd.</ label >"); sb.Append("<input type='number' min='0' max='10' name='qtd_tik' id='qtd_tik" + "123" + "'>"); lit1.Text = sb.ToString(); ////Button Button btnVenda = new Button(); btnVenda.Text = "ADD"; btnVenda.ID = "btn_Venda_" + id.ToString(); btnVenda.ControlStyle.CssClass = "sell_tik"; btnVenda.Width = 150; btnVenda.Height = 50; btnVenda.CommandArgument = id.ToString(); btnVenda.Click += new EventHandler(btn_Venda); ph1.Controls.Add(btnVenda); ////Button sb.Clear(); sb.Append("<small id='id_item' style='visibility: hidden'>" + id.ToString() + "</small>"); sb.Append("</div>"); sb.Append("</div>"); lit2.Text = sb.ToString(); }

    And the result of this demo:

    Below i will also provide another demo with less code and much more simple logic, please take a look:

    ASPX:

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                <asp:DataList ID="DataList1" runat="server" RepeatColumns="4" RepeatDirection="Horizontal" RepeatLayout="Table">
                    <ItemTemplate>
                        <div class='tick' style='background-color: #fff'>
                            <h5><%#Eval("title")%></h5>
                            <hr />
                            <div>
                                <img src='<%#Eval("image")%>' height="120px" width="150px" />
                                <br />
                                <label for='qtd_tik'>Qtd.</label>
                                <input type="number" min="0" max="10" name="qtd_tik" id='<%#"qtd_tik"+Eval("id")%>' />
                                <asp:Button ID="btn_Venda" runat="server" Text="ADD" OnClick="btn_Venda" Width="150px" Height="50px" />
                                <small id="id_item" style="visibility: hidden"><%#Eval("id")%></small>
                            </div>
                        </div>
                    </ItemTemplate>
                </asp:DataList>
            </div>
        </form>
    </body>
    </html>

    CS:

    protected void Page_Load(object sender, EventArgs e)
            {
                SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=DatabaseTestPool;Integrated Security=True");
                con.Open();
                SqlDataAdapter ad = new SqlDataAdapter("select * from Item", con);
                DataSet ds = new DataSet();
                ad.Fill(ds, "Users");
                DataTable dt = ds.Tables[0];
    
                DataList1.DataSource = dt;
                DataList1.DataBind();
            }
    
            protected void btn_Venda(object sender, EventArgs e)
            {
                Response.Write("123");
            }

    And the result of this one is just the same as the first demo:

    Best Regard,

    Yang Shen

    Wednesday, October 9, 2019 3:27 AM