(Forum Q & A Drops) How to dynamically add controls to TABLE and get the value of the control?

xiaoxiao2021-03-05  25

The effect of this example is: Each time button1, add a line in the table table1 (2 columns in the line, one column is a text box, one column is a drop-down box), and when the button is pressed, add a button, Click on this dynamically added button to output the value of all the controls in the table. Front desk:

<

FORM

id

= "Form1"

Method

= "POST"

Runat

= "Server"

>

<

ASP: TABLE

id

= "Table1"

Runat

= "Server"

>

ASP: TABLE

>

<

ASP: PlaceHolder

id

= "PlaceHolder1"

Runat

= "Server"

>

ASP: PlaceHolder

> <

Br

> <

Br

>

<

ASP: Button

id

= "Button1"

Runat

= "Server"

TEXT

= "Add a line"

>

ASP: Button

>

FORM

>

Place a table to dynamically add a control, place a PlaceHolder to dynamically add the button, press this button to get the value of the control in the table, and press the Button1 button to add a line. Backstage: Events of Button1 Buttons:

Private

Void

Button1_click

Object

Sender, System.EventArgs E)

{AddTextBoxs (); if (ViewState ["count"] == null) AddButton (); viewState ["count"] = convert.tate16 (viewState ["count"]) 1;}

Two ways: A row used to dynamically add a table, one is used to dynamically add a button (buttons are not added to Button1, so add IF (ViewState [":] == null) means that only the first time Add it when you load the button.

Private

Void

AddTextBoxs ()

{TABLEROW TR = New TableRow (); Tablecell TC1 = New TableCell (); TextBox T = New TextBox (); T.ID = "TB" Table1.Rows.count; tc1.trols.add (t); TableCell TC2 = new Tablecell (); DropDownList DPL = New DropdownList (); Dpl.Id = "DPL" Table1.Rows.count; for (int i = 0; i <10; i ) dpl.Items.Add (I.ToString ()); Tc2.controls.add (dpl); tr.cells.add (TC1); tr.cells.add (tc2); table1.Rows.Add (TR);} private

Void

AddButton ()

{Button B = New Button (); b. ID = "btn"; b.text = "button"; B.Click = New System.EventHandler (btn_click); Placeholder1.controls.Add (b);}

Finally, the event of the dynamically added button:

Private

Void

BTN_CLICK

Object

Sender, System.EventArgs E)

{For (INT i = 0; i ");}}

In fact, the control added control is not complicated. You only need to pay attention to it: Dynamically add controls need to be added again when postback, then how do you know that the button is pressed, or how do you know how many buttons have been pressed? Use a marker to store in ViewState. Page_Load Event:

Private

Void

Page_load

Object

Sender, System.EventArgs E)

{IF (viewState ["count"]! = Null) {for (int i = 0; i

转载请注明原文地址:https://www.9cbs.com/read-34818.html

New Post(0)