加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 一个更好的方法?找到ASP.NET控件,找到他们的id

发布时间:2020-12-15 07:43:56 所属栏目:百科 来源:网络整理
导读:我有一个方法找到所有控件,遍历它们,确定它们是文本框,下拉列表等等.检索它们的ID名称,并根据ID名称它将设置一个布尔语句(因此我会知道如果表格的那一部分是完整的,并将通过电子邮件发送给某一群人)不幸的是,这是通过太多的if语句完成的,并且想知道我是否可
我有一个方法找到所有控件,遍历它们,确定它们是文本框,下拉列表等等.检索它们的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");
      }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读