LINQ query to WebControl.Controls

匆匆过客 提交于 2019-12-08 06:32:35

问题


I have three TextBox controls on the page

<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">

and an event handler

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();
}

The meaning of this code is to automatically select TextBox with next TabIndex after page post back (see Little JB's problem). In reality I receive InvalidCastException because it's impossible to cast from System.Web.UI.LiteralControl (WebControl.Controls contains actually LiteralControls) to System.Web.UI.WebControls.WebControl.

I am interested is it possible to modify this aproach somehow to receive working solution? Thank you!


回答1:


OfType

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



回答2:


You should be able to use the OfType method, to only return controls of a given type.

e.g.

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



回答3:


The problem is that LiteralControl does not inherit from WebControl. It can't have the focus though, so it's OK to not select them. In your LINQ statement, add another condition checking for a WebControl. So your where line should be where control.TabIndex > changed_control.TabIndex && control is WebControl.



来源:https://stackoverflow.com/questions/178473/linq-query-to-webcontrol-controls

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!