Home » Asp.net

DataGrid - Setting focus after a TextBox TextChanged() event.

Asp.NET v2.0

Data grid with mulitple texboxes per row.

Each textbox has a TextChange() event wired up for data validation.

These events fire just fine, the data validation works just fine.

My issue is this:  User enters text into TextBox1 one then tabs into TextBox2. The cursor appears for a split second inside of TextBox2 then disappears as focus is being set somewhere else on the page.  I'm not sure how that change of focus is happening.

In this scenario, after tabbing out of TextBox1, how can I maintain focus on TextBox2 (and then subsequently TextBox3, TextBox4,etc..)


5 Answers Found


Answer 1

If you're using the server-side TextChanged event, you can do it the following way:

        DataGridItem item = (DataGridItem)((TextBox)sender).NamingContainer;
        TextBox TextBox2 = (TextBox)item.FindControl("TextBox2");

That would be on the TextChanged event for TextBox1. On TextBox2 TextChanged event, find control TextBox3 etc.

for a gridview, change 'DataGridItem' to 'GridViewRow'.

*Sorry if you posted this in the javascript forum intentionally - thought I'd give it a try, since you mentioned you're using the TextChanged event.


Answer 2

Thanks for the reply.

I've tried this approach previously and it does not alter the behavior.

Upon tabbing out of TB1, the cursor appears briefly in TB2 then disappears.

I feel like the answer lies somewhere in the TextChanged() events and the the DataGrid re-binding.


Answer 3

I feel like the answer lies somewhere in the TextChanged() events and the the DataGrid re-binding.

I should have said before - make sure you're binding the DataGrid within the if (!IsPostBack) {} code block.


Answer 4

Thanks again for the reply.

I think you've hit the nail on the head.

I'm using a 3rd party, multi-file upload control.  I bind the Items of that control to the DataGrid, then hide the FileUploader.

I have to bind on the Form_PreRender() event.  


Answer 5

No, I think you don't need to use TextChanged to validate the control. in my mind I guess that you can use js instead of textChanged event's checking:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="TestWebDemo.WebForm1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">

        function CheckTextValue(txtid, litid) {
            var txt = document.getElementById(txtid);
            if (txt.value == "") {
                alert("Not blank!");

    <form id="form1" runat="server">
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
                <asp:TemplateField HeaderText="Column1">
                        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
                        <asp:Literal ID="Literal1" runat="server"></asp:Literal>

                <asp:TemplateField HeaderText="Column2">
                        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>

                <asp:TemplateField HeaderText="Column1">
                        <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>

Your code behind:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace TestWebDemo
    public partial class WebForm1 : System.Web.UI.Page
        protected void Page_Load(object sender, EventArgs e)
            if (!IsPostBack)
                GridView1.DataSource = new string[] { "a", "b" };

        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
            if (e.Row.RowType == DataControlRowType.DataRow)
                TextBox txt1 = (TextBox)e.Row.FindControl("TextBox1");
                Literal lit = (Literal)e.Row.FindControl("Literal1");
                txt1.Attributes.Add("onblur", string.Format("CheckTextValue('{0}','{1}')",txt1.ClientID,lit.ClientID));

Then you can easily use Tab to move from one textbox to another...



Asp.NET v2.0

DataGrid with mulitple texboxes per row.

Each TextBox has AutoPostBack="True".

Each textbox has an OnTextChanged() event wired up for data validation.

These events fire just fine, the data validation works just fine.


My issue is this:  User enters text into TextBox1 one then tabs into TextBox2. The cursor appears for a split second inside of TextBox2 then disappears as focus is being set somewhere else on the page.  I'm not sure how that change of focus is happening.


In this scenario, after tabbing out of TextBox1, how can I maintain focus on TextBox2 (and then subsequently TextBox3, TextBox4,etc..)

In the OnTextChanged() handler for Textbox1, I've tried ..

     TextBox tb2 = (TextBox)myGridItem.FindControl("TextBox2");


This results in the same behavior: If the text in TB1 has changed and I tab out of TB1, the cursor appears briefly in TB2 then disappears.


I have a MaskedEditExtender with Mask="(999) 999-9999".

Now my problem is, if someone goes into the textbox and enters


Then they leave the textbox, and then see that they forgot to enter the area code, if they go back in there to enter the area code, it starts overwritting the other numbers instead of just adding to them. 


I've been doing a lot of testing of the textbox with the emulator(beta version).

What I've found is that the textbox does not fire the keydown event when, there is one character in the textbox, and you press the back button, on the InputScope namevalue "TelephoneNumber"

I know there is a known issue with the textchanged event firing twice, but is this problem known?



How can I bypass the TextChanged event if I populate the textbox during loading?

for example

When the VB Win form application starts it loads several text boxes with default information.
thus firing the TextChanged event. (which I don't want to happen)

I DO want to record any changes made by a user when he/she edits a textbox contents.


On the same App I am converting from VB6 I have a textbox that recieves data from another application. On the form I can see the data in the text box being sent to it from the other app but I can not get the textchanged event to fire.


What could be causing this and what is the best work around for it??


TIA Rick


I have a Textbox on my application that recieves data from another application via a sendmessage call from the other app.

I can see the data being entered in the textbox but the TextChanged event never fires when the text changes. I need to process the data that is sent but since the event does not fire I'm kinda stuck..

Can someone tell why this is happening and what I need to do to work around it????


TIA Rick


I have a textbox in my app in which I have code behind in the "onTextChanged" event that I'd like to execute  without doing an entire page post back . 

I can't use use AJAX not an option for me (corporate thing). 

Anyways, I have been struggling with the specifics on implementing ICallbackEventHandler. Or is than another way I can/should do this.

The code in the textChanged event pulls a dataset from the DB and does a validation.

Any advice is appreciated.






I have a textbox, under a specific circumstance, its textchanged event doesn't fired.

the keydown and previewkeydown do fired.

I assume there are other control intercept the keydown event and fool around it, probably did something over it.

but what can caused the textchanged event being cut off?

or any debugging approach for this?

i tried the AddHandler to the textchanged, in case its handled prop set to true that caused the cut off. but same, the event still don't get triggered under that special circumstance.


I am building a UserControl with several TextBox controls. The behavior I'm looking for, is everytime a value is changed in any TextBox, the UserControl refreshes a couple labels contained within it. Here's the code behind file that does the work:

Public Sub Refresh(ByVal sender As Object, ByVal e As System.Windows.Controls.TextChangedEventArgs)
    lblTotalHours.Content = txtHours.Text
End Sub

Now, here's a way to hook it up that works, however, "PreviewTextInput" gives the old textbox value to Refresh() and not the new one (as expected). I'm just writing this example because I had to confirm that my method of linking the event worked - and it does. My application runs fine even though the result isn't what I am looking for: (edit: to make it work, i also adapted the Refresh() declaration to match the PreviewTextInput delegate to TextCompositionEventArgs, if I recall correctly...)

<UserControl ...>
        <Style TargetType="x:Key TextBox">
            <EventSetter Event="PreviewTextInput" Handler="Refresh" />
        <TextBox Name="TxtHours" />
        <Label Name="LblTotalHours" />

Now, what I want to do is to use the TextChanged event instead. So I change the EventSetter line for the following:

            <EventSetter Event="TextChanged" Handler="Refresh" />

From that point, my application will not compile anymore, even though the UserControl does. I get the following error message in my app: "Cannot create instance of PhaseCalculator."

When I comment-out the code behind references to the UserControl elements (lblTotalHours and txtHours in this case), the application compiles fine once again. When I add MsgBox("Hello World") within the Refresh() sub, it also works fine in my application. If I do MsgBox(txtHours.Text), it doesn't work anymore.

I also tried the TextInput event instead of TextChanged, but I could never fire it up (it compiles, but I cannot seem to get inside the Refresh() sub at all).

Why can I access the UserControl elements from most events, but not from the TextChanged event?

For the record, I could use the TextChanged event for an individual TextBox by using the Visual Studio generated event (the one that ends with "Handles txtHours.TextChanged"). But I have over 40 textboxes and I think it would be a bad programming practice to create 40 individual functions, or add 40 different textbox names to the Handles clause.

Thanks for your help!


I have a text box that is bound (two way) to the following property:

 private String m_description;

        public String Description
            get { return m_description; }
                m_description = value;
                this.OnPropertyChanged("Description"); // This goes on to call the INotifyPropertyChanged.PropertyChanged event

But the data binding is only ever updated when the text loses focus. The TextChanged event does fire, but it doesn't  update the binding.

 I've had a look at the BindingExpression code via Reflector:

  if (this._targetObject is TextBox)
            this._targetIsTextBox = true;
            TextBox box = this._targetObject as TextBox;
            box.LostFocus += new RoutedEventHandler(this.TargetTextBoxLostFocus);
            if (this._targetProperty == TextBox.TextProperty)
                box.TextChanged += new TextChangedEventHandler(this.TargetTextBoxTextChanged);

It looks like it *should* work, but it isnt? The TargetTextBoxLostFocus function is definitely being called, I can see that in the call stack.

Any ideas?

Mark Ingram



In a Repeater I have a TextBox with its Text property bound. How can I capture the TextChanged event of that TextBox? I couldn't find any way for that on my own by now.




i have a textbox in a silverlight usercontrol and it is bound to a string property in the viewmodel class.

i would like the behavior that is whenever i type a letter in the textbox or delete, the binding should be fired. so, the string property setter should be called, and i can execute the action i want based on the actual value of the textbox.

thanks in advance for your help



I want to set the border for a DataGrid Row which is currently having the focus. But not the seleced row because when the Multi selection is enabled for the datagrid then there is a chance that multiple rows can be selected.

I need a solution in XAML

Thanks in advance!

Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question. This will help other members to find the solution easily.


How can I keep focus on caller textbox on textchange event or set focus on a given textbox according to a given value?

How can I know which textbox triggered the event if I need to use the same textchange method?

thanks in advance




I am doing a keyboard shortcut system for my application. I allow my users to set shortcuts such as a single key (like 'P' for example) or use keys such as Enter, Backspace, etc. However, this will clash when the user is entering text into a TextBox or such.

So I want to, inside my two functions that captures KeyDown and KeyUp event for the main window, detect if the user is entering text in TextBox. In psuedo code:

if (CurrentlyFocusedControl == TextBox)

It would make it easier for me in future coding since I would be able to just add more TextBoxes without having to manually, for each entry, add logic to "turn off" keyboard shortcuts while in edit mode.




Hello, I am doing an adornment extension that contains a simple textbox. This textbox appears in the text editor when I type a combination of keys. I am using this text box to insert a translation inside the text editor using google api. All works fine, but I have a little issue.

I want that the textbox which appears in the text editor gain the focus.

I have tried this but it doesn´t work:


Where "layer" is the IAdornmentLayer of my adornment.

Any ideas?




 I have a repeater control and a textbox in itemtemplate of repeater control. Now I am creating multiple textbox dynamically and bind to the repeater . so i m getting multiple textbox in repeater at runtime.

I need to set the focus on space bar key on these textbox. actully my requirement is that every textbox accept only one word.
Pls suggest me.



I am working with form having  multiple tabpages. I need  to set the focus on first textbox of all tabpages. I tried to declare the following when the form loads, but only txtbox1.select() is working. 

Private Sub frmMaintab_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load


'First textbox under first tab page


'First textbox under second tab page



'First textbox under third tab page



IDE: Visual Studio Pro 2005
Technologies: SQLServerExpress, VB.Net

I am curious....

How do you set focus on a textbox control in a modalPopup Panel once the TargetControl is activated?

I have tried putting it in the code behind for the TargetControl and it does not work.


Hi all ,

I am stuck in the set focus field in field in ajaxtoolkit : Tab  at codebehind when button click.

    Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click

    If StringUtil.IsStringEmpty(Me.ddlSex.SelectedValue) = True Then

       Page.ClientScript.RegisterStartupScript(Me.GetType, "ErrMsg", 
            JScriptUtil.ErrorMsg("Jantina (Sex): "

    End if

   End Sub


<< Previous      Next >>

Microsoft   |   Windows   |   Visual Studio   |   Sharepoint   |   Azure