简体   繁体   中英

Problems trying to find controls in a html element form asp.net

I need to count the controls in a form, but the form's name is dynamic. The problem is that if I use a variable to store the form name, it takes the argument as string. So I cannot use the Controls method to iterate the form controls and it's impossible to convert a string into an HTMLElement.

Here is what I have:

protected void SubmitForm(object sender, EventArgs e) {
  int CnTxt = 0;
  int CnChbx = 0;
  int CnDll = 0;
  int CnLstBx = 0;
  List < string > Params = new List < string > ();
  List < string > Ids = new List < string > ();
  foreach(Control c in this.form1.Controls) {
    if (c is TextBox) {
      Ids.Add(c.ID.ToString());
      CnTxt++;
    } else if (c is CheckBox) {
      CnChbx++;
    } else if (c is DropDownList) {
      CnDll++;
    } else if (c is ListBox) {
      CnLstBx++;
    }
  }
  for (int i = 0; i < Ids.Count; i++) {
    Params.Add(Ids[i].ToString());
  }
}

Please if you can help me, I'll be very grateful. And sorry for my bad english, I did my best.

I did it finally, I solved it by changing the foreach sintax:

    foreach (Control c in this.FindControl(Form.ID).Controls) 
{
 //Do whatever 
}

All you need to do is use the FindControl() method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM