LINQ query to WebControl.Controls
Asked Answered
S

3

1

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!

Sabellian answered 7/10, 2008 at 13:39 Comment(0)
J
5

OfType

from control in changed_control
  .Parent
  .Controls
  .OfType<WebControl>()
Jackelinejackelyn answered 7/10, 2008 at 13:48 Comment(0)
D
1

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
Defeatism answered 7/10, 2008 at 13:46 Comment(0)
R
0

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.

Rondarondeau answered 7/10, 2008 at 13:49 Comment(1)
LiteralControl does not have a TabIndex property, so this won't work.Jackelinejackelyn

© 2022 - 2024 — McMap. All rights reserved.