我有一个方法可以找到所有控件,遍历它们,确定它们是文本框,下拉列表等等。检索它们的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;
}
}
}
}
}
}
答案 0 :(得分:4)
为什么不使用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");
}
}
答案 1 :(得分:1)
很难理解代码背后的逻辑,但我确信它可以更容易编写。例如,你可以这样做:
DropDownBox box = FlattenHierachy(Page)
.Where(c => c is DropDownList)
.Cast<DropDownList>()
.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表达式,显然你可以使这个通用。所以你可以将它重用于不同的类型。这是尽可能接近您的代码的解决方案,但我想使用遍历页面的递归方法并将该谓词作为lambda表达式提供给该方法会更好。
答案 2 :(得分:0)
稍微清理一下代码,只包括每次检查一次。
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;
}
}
}
}
答案 3 :(得分:0)
我没有使用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 where 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);
}
}
}