how can i add about 50 checkbox controls to a web page dynamically and have them with events?
is this a possibility?
Printable View
how can i add about 50 checkbox controls to a web page dynamically and have them with events?
is this a possibility?
yes
Thank you for the answer to Part B of my post -
Is there someone who can show me or point me in the direction of the answer to Part A ?
Thanks
based on the code below that is taken from the link -
how would i create my 50 controls - they would all need a separate ID -
Is the intention to put a for-loop that adds my 50 controls with a new ID in the Page_Load ?
Code:namespace HowTos.Button
{
public class WebForm1 : System.Web.UI.Page
{
#region User Defined Code
System.Web.UI.HtmlControls.HtmlForm form;
private void Page_Load( System.Object sender, System.EventArgs e )
{
MyButton button = new MyButton();
button.ID = "Button1";
button.Click += new System.EventHandler( this.button_click );
form.Controls.Add( button );
}
private void button_click( System.Object sender, System.EventArgs e )
{
System.Web.UI.WebControls.Label lblMessage = new System.Web.UI.WebControls.Label();
lblMessage.ID = "lblMessage";
lblMessage.Text = "Button_Click Event Fired From Dynamically Created Button";
form.Controls.Add( new System.Web.UI.LiteralControl( "<P>" ) );
form.Controls.Add( lblMessage );
}
#endregion
#region Web Form Designer generated code
override protected void OnInit( System.EventArgs e )
{
InitializeComponent();
base.OnInit( e );
}
private void InitializeComponent()
{
this.Load += new System.EventHandler( this.Page_Load );
form = ( System.Web.UI.HtmlControls.HtmlForm )this.FindControl( "Form1" );
}
#endregion
}
}
You can give them all a seperate ID. Just increment an integer, append it to the id field, and hook them all back to the same handler, where you can ctype the sender to a checkbox, and check its id field, and doing different things using a select case statement on its id.
VB Code:
Private Sub Page_Load(byval sender as object, byval e as eventargs) _ Handles Mybase.Load If Not IsPostBack Then For i = 1 to 50 'make new checkbox Dim MyNewCheckBox As New System.Web.UI.CheckBox 'set whatever properties you want 'set its id MyNewCheckbox.Id = "mycheckbox" & i.ToString AddHandler myNewCheckBox.Click, AddressOf Mycheckboxhandler Next End If End Sub Private Sub myCheckBoxHandler (sender as Object, e as system.eventargs) 'narrow object to your checkbox Dim c As mycheckbox = CType(sender,checkbox) 'do a select based on the id Select (c.ID) Case "mycheckbox1" 'do something Case "mycheckbox2" 'do something else End Select End Sub