1

我在页面上有三个 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 的问题)。实际上,我收到 InvalidCastException,因为无法从 System.Web.UI.LiteralControl(WebControl.Controls 实际上包含 LiteralControls)转换为 System.Web.UI.WebControls.WebControl。

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

4

3 回答 3

5

类型

from control in changed_control
  .Parent
  .Controls
  .OfType<WebControl>()
于 2008-10-07T13:48:01.743 回答
1

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

例如

var nextcontrols = from WebControl control in     
                   Changed_control.Parent.Controls.OfType<TextBox>()... etc
于 2008-10-07T13:46:22.057 回答
0

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

于 2008-10-07T13:49:04.080 回答