Getting invalid values ​​from dynamically generated checkbox

I am trying to read from a dynamically created checkbox when a button is clicked. The problem is that after the checkbox is selected, further deactivation of the operation is not read correctly when the click is sent.

EDIT: A check box is first created when a radio book is selected, calling SetSelection , as shown.

The following is a snippet of code. Any idea what could be the problem?

 protected void Page_Load(object sender, EventArgs e) { if (this.IsPostBack) { .. GenerateDynamicUI(); } ... } private void GenerateDynamicUI(int selectedItem) { ... TableCell cellCheckBox = new TableCell(); CheckBox chkBox = new CheckBox(); chkBox.Text = "Consider all"; chkBox.ID = "chkAll"; cellCheckBox.Controls.Add(chkBox); TableRow chkRow = new TableRow(); chkRow.Cells.Add(cellCheckBox); table.Rows.Add(chkRow); } protected void btnSubmit_Click(object sender, EventArgs e) { ... bool isChecked = ((CheckBox)table.FindControl("chkAll")).Checked; } private void SetSelection() { int selectedItem = int.Parse(radiobuttonList.SelectedItem.Value); GenerateDynamicUI(selectedItem); pnlDynamic.Visible = true; } protected void radiobuttonList_SelectedIndexChanged(object sender, EventArgs e) { SetSelection(); } 
+4
source share
2 answers

I recreated your example and it works great. I can only imagine something else in your code responsible for unexpected behavior.

Try using the Page_PreInit event instead of Page_Load to re-create / manage dynamic controls:

 protected void Page_PreInit(object sender, EventArgs e) { // create controls here GenerateDynamicUI(); } 

Additional information: http://msdn.microsoft.com/en-us/library/ms178472.aspx

β€œNot Ready Right” I assume you mean that it stays True and never returns False after the first time you check it?

+4
source

it looks like you are announcing

 bool isChecked = ((CheckBox)table.FindControl("chkAll")).Checked; 

in btnSubmit if it were reset to false on every method call. try to declare it as a party. IE:

 bool isChecked; protected void btnSubmit_Click(object sender, EventArgs e) { ... isChecked = ((CheckBox)table.FindControl("chkAll")).Checked; } 
+2
source

Source: https://habr.com/ru/post/1391123/


All Articles