【问题标题】:LINQ query to WebControl.ControlsLINQ 查询到 WebControl.Controls
【发布时间】:2010-09-15 18:17:00
【问题描述】:

我在页面上有三个 TextBox 控件

<asp:TextBox ID="TextBox1" runat="server" AutoPostBack="True"
        OnTextChanged="TextBox_TextChanged" TabIndex="1">
<asp:TextBox ID="TextBox2" runat="server" AutoPostBack="True"
        OnTextChanged="TextBox_TextChanged" TabIndex="2">
<asp:TextBox ID="TextBox3" runat="server" AutoPostBack="True"
        OnTextChanged="TextBox_TextChanged" TabIndex="3">

和一个事件处理程序

protected void TextBox_TextChanged(object sender, EventArgs e)
{
    WebControl changed_control = (WebControl)sender;

    var next_controls = from WebControl control in changed_control.Parent.Controls
                        where control.TabIndex > changed_control.TabIndex
                        orderby control.TabIndex
                        select control;

    next_controls.DefaultIfEmpty(changed_control).First().Focus();
}

这段代码的意思是在页面回传后自动选择带有下一个 TabIndex 的 TextBox(参见Little JB's problem)。实际上,我收到 InvalidCastException,因为无法从 System.Web.UI.LiteralControl(WebControl.Controls 实际上包含 LiteralControls)转换为 System.Web.UI.WebControls.WebControl。

我很感兴趣是否有可能以某种方式修改这种方法以获得有效的解决方案?谢谢!

【问题讨论】:

    标签: asp.net linq web-controls


    【解决方案1】:

    OfType

    from control in changed_control
      .Parent
      .Controls
      .OfType<WebControl>()
    

    【讨论】:

      【解决方案2】:

      您应该能够使用 OfType 方法,只返回给定类型的控件。

      例如

      var nextcontrols = from WebControl control in     
                         Changed_control.Parent.Controls.OfType<TextBox>()... etc
      

      【讨论】:

        【解决方案3】:

        问题是 LiteralControl 没有从 WebControl 继承。但是它不能有焦点,所以不选择它们是可以的。在您的 LINQ 语句中,为 WebControl 添加另一个条件检查。所以你的 where 行应该是where control.TabIndex &gt; changed_control.TabIndex &amp;&amp; control is WebControl

        【讨论】:

        • LiteralControl 没有 TabIndex 属性,所以这不起作用。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-01-31
        • 1970-01-01
        • 1970-01-01
        • 2010-11-12
        • 2016-11-11
        • 2020-04-15
        • 1970-01-01
        相关资源
        最近更新 更多