更好的方法? 找到ASP.NET控件,找到他们的id

我有一个方法找到所有控件,遍历它们,确定它们是文本框,下拉列表等等。检索它们的ID名称,并根据ID名称它将设置一个布尔语句(因此我会知道如果表格的那一部分是完整的,并将通过电子邮件发送给某一群人)不幸的是,这是通过太多的if语句完成的,并且想知道我是否可以得到一些帮助使这个更易于管理

protected void getEmailGroup() { Control[] allControls = FlattenHierachy(Page); foreach (Control control in allControls) { if (control.ID != null) { if (control is TextBox) { TextBox txt = control as TextBox; if (txt.Text != "") { if (control.ID.StartsWith("GenInfo_")) { GenInfo = true; } if (control.ID.StartsWith("EmpInfo_")) { EmpInfo = true; } } } if (control is DropDownList) { DropDownList lb = control as DropDownList; if (lb.SelectedIndex != -1) { if (control.ID.StartsWith("GenInfo_")) { GenInfo = true; } if (control.ID.StartsWith("EmpInfo_")) { EmpInfo = true; } } } } } } 

为什么不使用Control.FindControl(string)方法?

来自: http : //msdn.microsoft.com/en-us/library/486wc64h.aspx

 private void Button1_Click(object sender, EventArgs MyEventArgs) { // Find control on page. Control myControl1 = FindControl("TextBox2"); if(myControl1!=null) { // Get control's parent. Control myControl2 = myControl1.Parent; Response.Write("Parent of the text box is : " + myControl2.ID); } else { Response.Write("Control not found"); } } 

很难理解代码背后的逻辑,但我确信它可以更容易编写。 例如,您可以执行以下操作:

 DropDownBox box = FlattenHierachy(Page) .Where(c => c is DropDownList) .Cast() .Where(d => d.SelectedIndex != -1) .FirstOrDefault(); if (box != null) { if (box.ID.StartsWith("GenInfo_")) { GenInfo = true; } if (box.ID.StartsWith("EmpInfo_")) { EmpInfo = true; } } 

如果你从seconde Where调用中提取lambda表达式,显然你可以使这个generics。 因此,您可以将其重用于不同类型。 这是尽可能接近您的代码的解决方案,但我想使用遍历页面的递归方法并将该谓词作为lambda表达式提供给该方法会更好。

清理了一些代码,只包括每次检查一次。

 protected void getEmailGroup() { Control[] allControls = FlattenHierachy(Page); foreach (Control control in allControls) { if (control.ID != null && ((control is TextBox && ((TextBox)control).Text = "" ) || (control is DropDownList && ((DropDownList)control).SelectedIndex != -1 )) { if (control.ID.StartsWith("GenInfo_")) GenInfo = true; if (control.ID.StartsWith("EmpInfo_")) EmpInfo = true; } } } } 

我没有使用Lambda表达式,而是创建了一个为我处理控件的方法,并根据控件的名称将该部分设置为true

 public bool setGroup(Control ctrl) { isAControl = false; //set a section to true, so it will pull the html if (ctrl.ID.StartsWith("GenInfo_")) { GenInfo = true; lstControls.Add(ctrl.ID.Replace("GenInfo_", "")); isAControl = true; return isAControl; } 

这里是我的代码的一小部分我只想检查某些控件(以加快速度)并且我通过每个控件,因为每个控件都有不同的方式来获取值(文本框将使用.text,其中dropdownlist将使用。了selectedValue)

 if(control is TextBox || control is DropDownList || control is RadioButton || control is RadioButtonList || control is CheckBox || control is CheckBoxList) { if (control is TextBox) { TextBox txt = control as TextBox; if (txt.Text != "" && txt.Text != "YYYY/MM/DD") { setGroup(control); if (isAControl) { string controlNoGroup = lstControls.Last(); strHtml = strHtml.Replace("@" + (controlNoGroup.ToString()) + "@", txt.Text); } } }