查询asp.net表单上的所有文本框,并使用linq使一个文本框不可见

时间:2015-03-26 11:17:49

标签: c# asp.net linq

我正在尝试将所有文​​本框放在asp.net表单上,期望ID=TextBox1并使其他所有内容都不可见。

这是我的代码。

Form.Controls
    .AsQueryable()
    .OfType<TextBox>()
    .Where(x => x.ID != "TextBox1")
    .ToList()
    .ForEach(y =>
{
    y.Visible = false;
});

我得到的例外是

System.ArgumentException was unhandled by user code
  HResult=-2147024809
  Message=source is not IEnumerable<>
  Source=System.Core
  StackTrace:
       at System.Linq.Queryable.AsQueryable(IEnumerable source)
       at _Default.ButtonA_Click(Object sender, EventArgs e) in c:\Users\Administrator\Documents\Visual Studio 2013\WebSites\WebSite1\Default.aspx.cs:line 17
       at System.Web.UI.WebControls.Button.OnClick(EventArgs e)
       at System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument)
       at System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)
       at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
       at System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
       at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
  InnerException: 

2 个答案:

答案 0 :(得分:3)

此异常的原因是多余AsQueryable()。如果某些ArgumentException来源没有实现 IEnumerable<T>,它会抛出T ControlsControlCollection,已实施IEnumerable,而不是IEnumerable<T>

以下是AsQueryable()的源代码:

public static IQueryable AsQueryable(this IEnumerable source) {
            if (source == null)
                throw Error.ArgumentNull("source");
            if (source is IQueryable)
                return (IQueryable)source;
            Type enumType = TypeHelper.FindGenericType(typeof(IEnumerable<>), source.GetType());
            if (enumType == null)
                throw Error.ArgumentNotIEnumerableGeneric("source");
            return EnumerableQuery.Create(enumType.GetGenericArguments()[0], source);
        }

注意以下几点:

 Type enumType = TypeHelper.FindGenericType(typeof(IEnumerable<>), source.GetType());
 if (enumType == null)
        throw Error.ArgumentNotIEnumerableGeneric("source");

ControlCollection不是通用IEnumerable,因此会抛出异常。

从代码中删除AsQueryable()。此外,Controls只会为您提供顶级控件。如果要迭代表单中的所有控件,请添加此方法:

  public static IEnumerable<Control> GetAllControls(Control parent)
    {
        foreach (Control control in parent.Controls)
        {
            yield return control;
            foreach (Control descendant in GetAllControls(control))
            {
                yield return descendant;
            }
        }
    }

然后:

   GetAllControls(Form).OfType<TextBox>()
        .Where(x => x.ID != "TextBox1")
        .ToList()
        .ForEach(y =>
    {
        y.Visible = false;
    });

答案 1 :(得分:0)

首先做OfType,然后是AsQueryable吗?

Form.Controls
    .OfType<TextBox>()
    .AsQueryable()
    .Where(x => x.ID != "TextBox1")
    .ToList()
    .ForEach(y =>
{
    y.Visible = false;
});