creating button in asp.net

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ganesh22
    Banned
    New Member
    • Sep 2007
    • 81

    creating button in asp.net

    Hi,
    the below code is for to create dynamically buttons in asp.net. my problem is at the first time i visited the page its working but if i visited the second time that buttons is not clearing. how to clear that?

    Code:
    using System;
    using System.Data;
    using System.Configuration;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;
    using System.Collections.Generic;
    
    public partial class Default2 : System.Web.UI.Page
    {
    
    static Button[] btn_arr = new Button[20];
    static int btn_count;
    
    protected void Page_Load(object sender, EventArgs e)
     {
       try
       {
          if (btn_arr[0] is Button) {
           //for each button saved in our array, recreate it
           foreach (Button button in btn_arr) {
             add_button(button);
           }
          }
        }
        catch (Exception ex)
        {
          lblStatus.Text += ex.Message.ToString();
        }
     }
    
     protected void add_button(Button button)
     {
      try
      {
          TableRow tr = new TableRow();
          TableCell tc = new TableCell();
       tc.Controls.Add(button);
       tr.Cells.Add(tc);
       ctrlTable.Rows.Add(tr);
       //pnlMain.Controls.Add(new LiteralControl("<br>"));
      }
      catch (Exception ex)
      {
       lblStatus.Text += ex.Message.ToString();
      }
     }
    
     protected void btnSubmit_Click(object sender, EventArgs e)
     {
      try
      {
       //create a new instance of the control
       Button new_button = new Button();
       new_button.ID = txtID.Text;
       new_button.ForeColor = System.Drawing.Color.FromName(txtForeColor.Text);
       new_button.Text = txtText.Text;
       //add button to button array
       btn_arr[btn_count++] = new_button;
       //call our add function
       add_button(new_button);
       lblStatus.Text += "Created button " + new_button.ID + " and of color " + new_button.ForeColor;
      }
      catch (Exception ex)
      {
       lblStatus.Text += ex.Message.ToString();
      }
    
     }
    
    }
  • kenobewan
    Recognized Expert Specialist
    • Dec 2006
    • 4871

    #2
    Sounds like you are having trouble with postbacks. When you don't want code to execute in the page load everytime there is a postback, you need to preserve it using not page.ispostback method. HTH.

    Comment

    Working...