locked
need help for Dynamically created image button click event RRS feed

  • Question

  • User872370986 posted

    if (DropDownList1.SelectedItem.Text == "Hostel1")

                {

                    Pnl11.Visible = true;

                    mc.connect();

                    mc.ds.Clear();

                    string selectSQL = "select * from hostels where hostelname=" + "'" + DropDownList1.SelectedItem.Text + "'";

                    mc.comm.Connection = mc.con;

                    mc.con.Open();

                    SqlCommand cmd = new SqlCommand(selectSQL, mc.con);

                    SqlDataReader dr = cmd.ExecuteReader();

                    if (dr != null)

                    {

                        while (dr.Read())

                        {

                            int capacity = Convert.ToInt32(dr["newcapacity"]);

                            string room_no = Convert.ToString(dr["roomno"]);

                        if (capacity == 0)

                            {

                                ImageButton img = new ImageButton();

                                img.ID = room_no;

                            img.ImageUrl = "~/Images/booked_img.gif";

                            img.AlternateText = room_no;

                            img.ToolTip =  " No seats Available";

                            img.Style.Add("margin", "5px");

                            img.Style.Add("height", "25px");

                            img.Style.Add("Width", "45px");

                            img.Enabled = false;

                                Pnl11.Controls.Add(img);

     

                            }

                            else

                            {

                                ImageButton img = new ImageButton();

                                img.ID = room_no;

                                img.AlternateText = room_no ;

                            

                                img.ToolTip = capacity + " seats Available";

                                img.Style.Add("margin", "5px");

                                img.Style.Add("height", "25px");

                                img.Style.Add("Width", "45px");

                                img.ImageUrl = "~/Images/selected_img.gif";

                                img.Enabled = true;

                            img.Click += new ImageClickEventHandler(img_Click);

                            Pnl11.Controls.Add(img);

                            }

                        }

                    }

     

                }

            

        }   

        protected void img_Click(object sender, ImageClickEventArgs e)

        {

            string url = ((ImageButton)sender).ID.ToString();

    Textbox3.text=url;

            

        }

    can anybody tell me why this click event is not firing

    Wednesday, June 13, 2018 10:10 AM

All replies

  • User475983607 posted

    Dynamic controls must be recreated on every post back in the Page_Initi or Page_Load event.  The framework does not know about controls that do not exist in the markup (or designer file).  

    Or use standard ASP Web Forms convection and render the image button within a data bound control.

    Wednesday, June 13, 2018 10:18 AM
  • User-330142929 posted

    Hi Indujoshi09,

     

    According to your description, I suggest you could create control dynamically in the Page_Init/Page_load event, once the page postbacks these controls will not be generated correctly.

    I have made a demo, wish it could be useful to you.

    Aspx.

           <div>
                <asp:PlaceHolder ID="Placeholder1" runat="server"></asp:PlaceHolder>
                <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
            </div>

    Code behind.

    protected void Page_Init(object sender, EventArgs e)
            {
                Button button = new Button();
                button.ID = "Button1";
                button.Text = "Click";
                button.Click += new EventHandler(Button1_Click);
                this.Placeholder1.Controls.Add(button);
            }
            protected void Page_Load(object sender, EventArgs e)
            {
                //Button button = new Button();
                //button.ID = "Button1";
                //button.Text = "Click";
                //button.Click += new EventHandler(Button1_Click);
                //this.Placeholder1.Controls.Add(button);
            }
            protected void Button1_Click(object sender, EventArgs e)
            {
                this.Label1.Text = DateTime.Now.ToLongTimeString();
            }

    How it works.

    Please feel free to let me know if the problem still exists.

    Best Regards,

    Abraham

    Tuesday, June 19, 2018 3:30 AM
  • User872370986 posted

    Hi Abraham

    Thanks for your valuable reply. but my problem is buttons are created on the basis of values selected from drop-down. so this cant be done in page load because on the basis of values selected these buttons are created. so kindly suggest any solution .

    Thanks and Regards

    Indu Joshi

    Wednesday, June 20, 2018 6:54 AM
  • User872370986 posted

    Hi 

    Thanks for your valuable reply. but my problem is buttons are created on the basis of values selected from drop-down like there are 4-5 hostels with different capacity so on the basis of the hostel selected this room image buttons are created  so this cannot be done on the page load as we need to select the hostel first then view of that hostel. . so kindly suggest any solution .

    Thanks and Regards

    Indu Joshi

    Wednesday, June 20, 2018 6:58 AM
  • User475983607 posted

    Thanks for your valuable reply. but my problem is buttons are created on the basis of values selected from drop-down like there are 4-5 hostels with different capacity so on the basis of the hostel selected this room image buttons are created  so this cannot be done on the page load as we need to select the hostel first then view of that hostel. . so kindly suggest any solution .

    Not true! 

    You must write code to remember the state of the page when the controls are created.  Then recreate those control when the page loads.  Keep in mind this is not a new programming problem in ASP Web Forms.  This question is asked several times a week for the last 18 years.  

    The common approach is binding controls within a data bound control like a Repeater.  Using the frameworks as intended registers the controls with ASP Web Forms State Management.  Your custom design requires you to write code that manages state as the framework cannot read your mind or guess your programming intentions..

    Wednesday, June 20, 2018 10:29 AM
  • User872370986 posted

    protected void img_Click(object sender, ImageClickEventArgs e)

        {

            string url = ((ImageButton)sender).ID.ToString();

    Textbox3.text=url;

            

        }

    Can you please figure out why this event is not firing?

    Wednesday, June 20, 2018 10:34 AM
  • User475983607 posted

    Can you please figure out why this event is not firing?

    Events are register in the markup up or Page_Init event but you have not shown this bit of the code. 

    Wednesday, June 20, 2018 10:49 AM
  • User872370986 posted

    HI

    by reading from one example online i added this code, now my page is retaining value after click but click event is not firing. 

    img.OnClientClick = "return false;";

    Wednesday, June 20, 2018 10:57 AM
  • User475983607 posted

    Indujoshi09

    HI

    by reading from one example online i added this code, now my page is retaining value after click but click event is not firing. 

    img.OnClientClick = "return false;";

    The code shown stops the img control from submitting a POST and if the POST is stopped then the event will never fire. Why are you stopping the POST? 

    Wednesday, June 20, 2018 11:03 AM
  • User872370986 posted

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Configuration;
    using System.Data;
    using System.Data.SqlClient;
    using System.IO;
    using System.Web.Security;
    using System.Web.UI.HtmlControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Xml.Linq;
    using System.Drawing;
    using System.Drawing.Imaging;

    public partial class hostelmain1 : System.Web.UI.Page
    {
    public class myclass
    {
    public SqlConnection con = new SqlConnection();
    public SqlCommand comm = new SqlCommand();
    public SqlCommandBuilder cb = new SqlCommandBuilder();
    public SqlDataAdapter da = new SqlDataAdapter();
    public DataSet ds = new DataSet();
    public DataSet ds1 = new DataSet();
    public DataSet ds2 = new DataSet();
    public DataSet ds3 = new DataSet();
    public void connect()
    {
    con.ConnectionString = "Data Source=localhost;Initial Catalog=alumni;Persist Security Info=True;User ID=sa;Password=parulsaini";
    }
    public myclass()
    {
    //
    // TODO: Add constructor logic here .
    //
    }
    }
    myclass mc = new myclass();
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void Button1_Click(object sender, EventArgs e)
    {

    }
    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
    Button3.Visible = true;
    mc.connect();
    mc.ds.Clear();

    mc.comm.CommandText = "select sum(roomcapacity) from hostels where hostelname=" + "'" + DropDownList1.SelectedItem.Text + "'";
    mc.comm.Connection = mc.con;
    mc.da = new SqlDataAdapter(mc.comm);
    mc.cb = new SqlCommandBuilder(mc.da);
    mc.da.Fill(mc.ds, "hostels");
    Label44.Text = mc.ds.Tables["hostels"].Rows[0].ItemArray.GetValue(0).ToString();
    mc.comm.CommandText = "select count(*) from seatallot where hostelname=" + "'" + DropDownList1.SelectedItem.Text + "'";
    mc.comm.Connection = mc.con;
    mc.da = new SqlDataAdapter(mc.comm);
    mc.cb = new SqlCommandBuilder(mc.da);
    mc.da.Fill(mc.ds, "seatallot");
    Label46.Text = mc.ds.Tables["seatallot"].Rows[0].ItemArray.GetValue(0).ToString();

    }
    protected void roomselect(string hn)
    {
    Pnl11.Visible = true;
    mc.connect();
    mc.ds.Clear();
    string selectSQL = "select * from hostels where hostelname=" + "'" + hn + "'";
    mc.comm.Connection = mc.con;
    mc.con.Open();
    SqlCommand cmd = new SqlCommand(selectSQL, mc.con);
    SqlDataReader dr = cmd.ExecuteReader();
    if (dr != null)
    {
    while (dr.Read())
    {
    int capacity = Convert.ToInt32(dr["newcapacity"]);
    string room_no = Convert.ToString(dr["roomno"]);
    if (capacity == 0)
    {
    ImageButton img = new ImageButton();
    img.Attributes.Add("ID", room_no);
    img.ImageUrl = "~/Images/booked_img.gif";
    img.AlternateText = "image";
    img.ToolTip = " No seats Available";
    img.Style.Add("margin", "5px");
    img.Style.Add("height", "25px");
    img.Style.Add("Width", "45px");
    img.Attributes.Add("id", ID.ToString());
    img.Enabled = false;
    Pnl11.Controls.Add(img);
    img.OnClientClick = "return false;";

    }
    else
    {
    ImageButton img = new ImageButton();
    img.Attributes.Add("ID", room_no);
    img.AlternateText = room_no;
    img.ToolTip = capacity + " seats Available";
    img.Style.Add("margin", "5px");
    img.Style.Add("height", "25px");
    img.Style.Add("Width", "45px");
    img.ImageUrl = "~/Images/selected_img.gif";
    img.Enabled = true;
    img.Attributes.Add("id", ID.ToString());
    Pnl11.Controls.Add(img);
    img.OnClientClick = "return false;";
    img.Click += new ImageClickEventHandler(img_Click);
    }
    }
    }
    }
    protected void img_Click(object sender, ImageClickEventArgs e)
    {

    }

    protected void Button3_Click(object sender, EventArgs e)
    {

    Panel2.Visible = true;
    if (DropDownList1.SelectedItem.Text == "Sutlej Hostel")
    {
    string hname = DropDownList1.SelectedItem.Text;
    roomselect(hname);
    }
    if (DropDownList1.SelectedItem.Text == "Alaknanda Hostel")
    {
    string hname = DropDownList1.SelectedItem.Text;
    roomselect(hname);
    }

    if (DropDownList1.SelectedItem.Text == "Brahmaputra Hostel")
    {
    string hname = DropDownList1.SelectedItem.Text;
    roomselect(hname);
    }
    if (DropDownList1.SelectedItem.Text == "International Hostel")
    {
    string hname = DropDownList1.SelectedItem.Text;
    roomselect(hname);
    }
    if (DropDownList1.SelectedItem.Text == "Krishna Hostel")
    {
    string hname = DropDownList1.SelectedItem.Text;
    roomselect(hname);
    }
    if (DropDownList1.SelectedItem.Text == "Narmada Hostel")
    {

    string hname = DropDownList1.SelectedItem.Text;
    roomselect(hname);

    }
    if (DropDownList1.SelectedItem.Text == "Kaveri Hostel-Old Wing")
    {
    string hname = DropDownList1.SelectedItem.Text;
    roomselect(hname);
    }

    if (DropDownList1.SelectedItem.Text == "Kaveri Hostel-Amrawati Wing")
    {
    string hname = DropDownList1.SelectedItem.Text;
    roomselect(hname);
    }
    if (DropDownList1.SelectedItem.Text == "Kaveri Hostel-Hemawati")
    {
    string hname = DropDownList1.SelectedItem.Text;
    roomselect(hname);
    }

    }

    }

    this is complete code of my page if you can spare 10-15 minutes and find out the mistake or any solution kindly suggest. i will be highly thankful.

    Wednesday, June 20, 2018 11:05 AM
  • User475983607 posted

    It seems you are ignoring the advice and sample code.  This might be due to being a new Web Forms programmer.

    I suggest that you set aside time to learn ASP Web Forms.  The Getting Started tutorials on this site are very good and will help you become acquainted with common programing patterns used in Web Forms.

    https://www.asp.net/web-forms

    You should have a much better understanding of Web Forms after completing a few tutorials which you can apply to the current programming problem.

    Wednesday, June 20, 2018 11:20 AM
  • User872370986 posted

    I am trying the  IsPostBack method but again its not working. 

    Friday, June 22, 2018 10:07 AM
  • User475983607 posted

    I am trying the  IsPostBack method but again its not working. 

    What is "not working"?

    Did you refactor your code and use a data bound control as suggested?  Did you write code to remember the state of the dynamic controls and add the controls in the Page_Init or Page_Load events?

    Friday, June 22, 2018 10:59 AM
  • User-1171043462 posted

    Refer

    Handle Click event of dynamically generated Button, LinkButton and ImageButton in ASP.Net

    Also there's a Video for better understanding.

    Saturday, June 23, 2018 1:37 PM
  • User872370986 posted
    public class Sample : Control {
        private int currentIndex = 0;
    
        protected override void OnInit(EventArgs e) {
            Page.RegisterRequiresControlState(this);
            base.OnInit(e);
        }
    
        protected override object SaveControlState() {
            return currentIndex != 0 ? (object)currentIndex : null;
        }
    
        protected override void LoadControlState(object state) {
            if (state != null) {
                currentIndex = (int)state;
            }
        }
    }

    Sir do i have to write code like this to save the state?

    Monday, June 25, 2018 9:10 AM
  • User-1171043462 posted

    From where you got this code?

    Monday, June 25, 2018 9:19 AM
  • User872370986 posted

    i got this from some forum

    Wednesday, June 27, 2018 10:25 AM
  • User-1171043462 posted

    No, you don't need. Just download sample from my article and try yourself.

    Wednesday, June 27, 2018 11:02 AM
  • Wednesday, August 8, 2018 8:56 PM