Many times in our applications we need to add controls to a panel using add button and we dont know how many times the user clicks.This article deals with one such need to create texboxes on click of a button.First we have to add a panel named pnlmain and button named btnaddbr in design view.
Add this code in code view
static TextBox[] btn_arr = new TextBox[20]; static int btn_count; protected void Page_Load(object sender, EventArgs e) { try { if (btn_arr[0] is TextBox) { //for each button saved in our array, recreate it foreach (TextBox txtbx in btn_arr) { add_textbox(txtbx); } } } if (!Page.IsPostBack) { pnlMain.Controls.Clear(); btn_count = 0; foreach (TextBox txtbx in btn_arr) { if (txtbx != null) { btn_arr[k] = null;
} k = k + 1; } } }
protected void add_textbox( TextBox txtbx) { try { //add to a container on the page pnlMain.Controls.Add(txtbx); //add a spacer after the control pnlMain.Controls.Add(new LiteralControl(" ")); } catch (Exception ex) { } } protected void btnaddbr_Click(object sender, EventArgs e) { TextBox new_txtbx = new TextBox(); new_txtbx.ID = "txtbr" + int.Parse((btn_count+1).ToString()); new_txtbx.Attributes.Add("runat", "server"); btn_arr[btn_count++] = new_txtbx; add_textbox(new_txtbx); }
In the code view we are declaring static textbox array to create textboxes and and static int btn_count to get the text box count.On the click of the button we are creating a textbox and adding it to panel using add_textbox function. What if the page refreshes ,the controls are dynamcially created and we dont know how many controls are added by user ,so inorder to avoid that situation we have stored the texboxes in static textbox array.We retrieve the textbox array on page load using condition given below
try { if (btn_arr[0] is TextBox) { //for each button saved in our array, recreate it foreach (TextBox txtbx in btn_arr) { add_textbox(txtbx); } } }
if the page is posted for first time ,we need to clear textboxes which are present in static textbox array for that we are using this condition
if (!Page.IsPostBack) { pnlMain.Controls.Clear(); btn_count = 0; foreach (TextBox txtbx in btn_arr) { if (txtbx != null) { btn_arr[k] = null;
} k = k + 1; } }
Hope things are clear.
|
| Author: H. CHRISTOPHER 20 Dec 2008 | Member Level: Silver Points : 0 |
Very Nice!
|