Solved

Dynamic Image Button

Posted on 2006-07-03
13
909 Views
Last Modified: 2011-10-03
I am trying to dynamically create image buttons. Only one is being created in my for loop. Am i missing something?

 public void Button1_Click1(object sender, EventArgs e)
    {
        Table table = (Table)this.FindControl("_table");
        TableRow tr = new TableRow();
        TableCell tdLabel = new TableCell();
        TableCell tdTextBox = new TableCell();

        int i = 0;

        for (i = 0; i < 4; i++)
        {

            ImageButton button = new ImageButton();
            button.Click += new ImageClickEventHandler(Button1_Click);
            button.ID = Convert.ToString(i);
           
            tdLabel.Controls.Add(button);

            tr.Cells.Add(tdLabel);

            table.Rows.Add(tr);
        }
    }
0
Comment
Question by:LeeHenry
  • 5
  • 4
  • 4
13 Comments
 
LVL 16

Expert Comment

by:Edwin_C
ID: 17034442
public void Button1_Click1(object sender, EventArgs e)
    {
        Table table = (Table)this.FindControl("_table");
         TableCell tdTextBox = new TableCell();

        int i = 0;

        for (i = 0; i < 4; i++)
        {

            ImageButton button = new ImageButton();
            button.Click += new ImageClickEventHandler(Button1_Click);
            button.ID = Convert.ToString(i);
           
         TableCell tdLabel = new TableCell();  //try moving this into the loop
         TableRow tr = new TableRow();
 
          tdLabel.Controls.Add(button);

            tr.Cells.Add(tdLabel);

            table.Rows.Add(tr);
        }
    }
0
 
LVL 6

Author Comment

by:LeeHenry
ID: 17034714
It is working in my for loop, but when I click the button again.. new  buttons are not created. Is there a way for me to create a new button, everytime i press Button1_Click1?

0
 
LVL 16

Expert Comment

by:Edwin_C
ID: 17034799
This is because the Table control did not "remember" its content after postback.  Therefore after each click, your page loads a completely new (i.e. empty) Table control and your code add buttons an empty table again.

Hence you need to remember the required content (I recommend using ViewState) after each change (add/edit/delete)and then reload the content after postback and render the table accordingly.

Here is a simple code to add a row in a table after each click.  Hope that can show my idea.

      public class frmAddRow: System.Web.UI.Page
      {
            protected System.Web.UI.WebControls.Button Button1;
            protected System.Web.UI.WebControls.Table Table1;
            private System.Collections.ArrayList textlist;
      
            private void Page_Load(object sender, System.EventArgs e)
            {
            }

            private void Button1_Click(object sender, System.EventArgs e)
            {
                  object obj = ViewState["list"];
                  
                  textlist = obj==null?new System.Collections.ArrayList():(System.Collections.ArrayList)obj;
                  textlist.Add(DateTime.Now.ToString("hh:mm:ss"));
                  ViewState["list"] = textlist;
                  renderTable();
            }

            private void renderTable()
            {
                  foreach (object obj in textlist)
                  {
                        TableCell cell = new TableCell();
                        cell.Text = (string)obj;
                        TableRow row = new TableRow();
                        row.Cells.Add(cell);
                        Table1.Rows.Add(row);
                  }
            }
      }

Edwin
0
 
LVL 9

Expert Comment

by:zaghaghi
ID: 17035800
what is _table, i want to know this to simulate your project
0
 
LVL 9

Expert Comment

by:zaghaghi
ID: 17036472
I use this code and it works:

1)in page load write this:

private Page_Load(...)
{
      if( !IsPostBack)
      {
            ViewState.Add("numberOfRows", 0);
      }
      CreateRows();
}

as you see in page load, first i add a variable to viewstate to store the number of rows that generated until now

and then in page load call CreateRows function that describe bellow to create the rows:


private void CreateOneRow(HtmlTable table)
{
      HtmlTableRow tr = new HtmlTableRow();

      int i=0;

      for(i=0; i<4; i++)
      {
            HtmlTableCell tdLabel = new HtmlTableCell();

            ImageButton button = new ImageButton();
            TextBox txt = new TextBox();
            button.Click += new ImageClickEventHandler(button_Click);
            tdLabel.Controls.Add(button);
            tdLabel.Controls.Add(txt);

            tr.Controls.Add(tdLabel);
      }

      table.Controls.Add(tr);
}

private void createRows()
{

      int size;
      if(ViewState["numberOfRows"]==null)
            size=0;
      else
            size=(int)ViewState{"numberOfRows"];

      int i;
      for(j=0; j<size; j++)
            createOneRow(_table);

}

0
 
LVL 9

Expert Comment

by:zaghaghi
ID: 17036485
2) handle Button On Click event to add more rows to the table

private void Button1_Click(...)
{
       int lastSize;
       if(ViewState["numberOfRows"]==null)
              lastSize = 0;
       else
              lastSize = (int) ViewState["numberOfRows"];

       ViewState["numberOfRows"] = lastSize + 1;

       createOneRow(_table);
}

in this function  first increament lastSize for later use, and then add one row to the table

hope this can help you
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 6

Author Comment

by:LeeHenry
ID: 17039833
Edwin,

I tried your suggestion, but i may be missing something.. i am getting a serializable error when casting to an imagebutton.

public partial class Default2 : System.Web.UI.Page
{
     
        protected System.Web.UI.WebControls.Table Table1;
        private System.Collections.ArrayList textlist;
   
        private void Page_Load(object sender, System.EventArgs e)
        {
        }

        public void Button1_Click(object sender, System.EventArgs e)
        {
            object obj = ViewState["list"];
            But button = new But();
            ImageButton myImagBut = button.getButton();

            textlist = obj == null ? new System.Collections.ArrayList() : (System.Collections.ArrayList)obj;
            textlist.Add(myImagBut);
            ViewState["list"] = textlist;
            renderTable();
        }

    private void renderTable()
    {
        foreach (object obj in textlist)
        {
           
                TableCell cell = new TableCell();
                cell.Controls.Add((ImageButton)obj);
                TableRow row = new TableRow();
                row.Cells.Add(cell);
                _table.Rows.Add(row);
           
        }
    }
0
 
LVL 16

Expert Comment

by:Edwin_C
ID: 17039864
I don't think you can add the imagebutton to the arraylist and then save in viewstate.  This is what the error about.  

You should just save the information required for rebuidling the buttons in table.  It depends on your application.  It can be as simple as just need the number of buttons and then you create the buttons with the exact number of rows. In that case, you can save the integer value of number of buttons only in a single viewstate variable.  If the scenario is more complicated and each button has its own label which cannot be derived by logic (maybe by user's choice), then you need to save the labels (i.e. a string) using arraylist and then rebuild the buttons in renderTable().  Do not save unnecessary data in viewstate.

If you are not clear about what I say, please tell me more about your application.

Edwin
0
 
LVL 6

Author Comment

by:LeeHenry
ID: 17046270
What I am trying to do is allow users to be able to mirror the functionality of a windows application. For example, on my web application, I want to have a "create new directory" button. When they press that button, a new image button displays(the image url will be a folder icon). So if they press the create new directory button 7 times.. I should have 7 new image buttons.. It appears that what I have works if I put it in a loop, but since i don't know how many directories the user will try to create, I just need it to add a new one when they press the button.
0
 
LVL 9

Accepted Solution

by:
zaghaghi earned 500 total points
ID: 17046331
if you use my solution( save number of controls in ViewState ) can do what you want
0
 
LVL 6

Author Comment

by:LeeHenry
ID: 17046379
thanks.. i was going to give that a try next..
0
 
LVL 6

Author Comment

by:LeeHenry
ID: 17046955
Edwin,
I meant to split and give you some points too.. if there is a way to get that to you let me know.. thanks for all the help guys.

0
 
LVL 16

Expert Comment

by:Edwin_C
ID: 17048605
Yes, zaghaghi's solution can do the job in your case.

Edwin
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

In .NET 2.0, Microsoft introduced the Web Site.  This was the default way to create a web Project in Visual Studio 2005.  In Visual Studio 2008, the Web Application has been restored as the default web Project in Visual Studio/.NET 3.x The Web Si…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
This demo shows you how to set up the containerized NetScaler CPX with NetScaler Management and Analytics System in a non-routable Mesos/Marathon environment for use with Micro-Services applications.

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now