Question

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!

Was it helpful?

Solution

OfType

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

OTHER TIPS

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

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top