How to find out if a dynamically created checkbox was checked

I created a dynamic CheckBoxin event Page_Loadon my ASP.NET website.

Here is the code

 public CheckBox[] chk;
 chk[i] = new CheckBox();
 chk[i].ID = "chk" + dt1.Rows[i]["SubjectName"].ToString();
 chk[i].Text = dt1.Rows[i]["SubjectName"].ToString();                   
 PanelSubject.Controls.Add(chk[i]);

How can I later find out if CheckBoxthis method was installed by the specified user?

+4
source share
3 answers

You must register an event for this dynamically generated check box, as shown below:

 public CheckBox[] chk;
 chk[i] = new CheckBox();
 chk[i].ID = "chk" + dt1.Rows[i]["SubjectName"].ToString();
 chk[i].Text = dt1.Rows[i]["SubjectName"].ToString();                   
 chk[i].CheckedChanged += WebForm1_CheckedChanged;
 PanelSubject.Controls.Add(chk[i]);


 void WebForm1_CheckedChanged(object sender, EventArgs e)
 {
      throw new NotImplementedException();
 }

Also you need to save chk[i].AutoPostBack = true;

+2
source

Use javascript

In the script:

    var x=document.getElementById("IdCheckbox").checked
if(x==1)
{
//checked
}
else
{
// unchecked
}

or

function validate() {
        if (document.getElementById('idofcheckbox').checked) {
            alert("checked");
        } else {
            alert("You didn't check it! Let me check it for you.");
        }
    }

or if you use jquery then

if($("#idofcheckbox").is(':checked'))
      // checked
else
     // unchecked

another method

$("#idcheckbox").attr("checked") ? alert("Checked") : alert("Unchecked");
+1
source

, , Findcontrol,

    string SubjectName = dt1.Rows[i]["SubjectName"].ToString();

    CheckBox currentCheckBox = PanelSubject.FindControl("chk" + SubjectName) as CheckBox;
    if( currentCheckBox !=null   )
    {
         if( currentCheckBox.Checked )
         {
             //here is your code 
             string alertMessage = string.Format("Subject {0} is checked !!!", SubjectName );
         }
     }
+1
source

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


All Articles