.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
david stephan
Gaurav Pal
Post New Web Links

Generated controls - skipping focus event - C# + JS

Posted By:      Posted Date: August 25, 2010    Points: 0   Category :ASP.Net

Ok, here is my senario.

A random (6-15) amount of textboxes are generated. Each textbox represents only one character. From those textboxes, three of them (at a random position) are enabled and the rest disabled.


When I put a character in any enabled textbox, it must put the focus on the next enabled textbox.


Textbox IDs go from 'char0' to 'char15' OR 'char0' to 'char12' OR ...

All the textboxes are generated so I can't set up specific focus events for each textbox because the designated control is unknown at design time.

Here is my attempt:


<script type="text/javascript">
    function abc(nextfocus)


for (int i = 0; i < focusableControls.Length-1; i++)
focusableControls[i].ClientSideEvents.KeyDown = "abc(" + focusableControls[i + 1].ID + ")";


focusableControls is an array with all the textboxes in that can get focus. It is also in the right order.

Things I want to find out:

How will I send the textbox out of focus

View Complete Post

More Related Resource Links

lossing focus from model pop up window controls


hi i using a model pop up window with some textbox but when i click on textbox of model pop up focus move to back to page textbox control plz help me 

Adding client event handlers to an ASP.NET controls programmatically



I want to add client event handlers to ASP.NET controls (For example: GridView/Button ) programmatically to ASP.NET.

I am aware of "onclick" event handler, so my code would be

GridView1.Attributes.Add("onclick", "JSGridViewFunction()");

Button1.Attributes.Add("onclick", "JSButtonFunction()");

I want to know what are all the event handlers that are available for (or that can be added to)  ASP.NET controls.

For example, I want to add "onsort" event handler to ASP.NET GridView control.

But the following code fails

GridView1.Attributes.Add("onsort", "JSGridViewFunction()");

Please help.


Cannot retrieve values of dynamically generated controls

Hi All, I am creating a user control which contains checkboxes and labels that needs to be created on fly. The dynamic generation of these controls depend on the values retreived from a SPlist. I have several panels that display items queried from the list on the basis of a selection criteria. On a button click event I need to capture all the selected values from the controls that were generated dynamically.  When I traverse each dynamic control that I added to the panel, I dont see their values. I tried using recursive retrieval of the control from the page as well but it just behaves crazy, it treats a radio button as a checkbox and returns a value that I am not looking for. I am not using the the page_load() or any other event, I use the button handler on my custom method. I was thinking for ViewState, ControlsState or SessionState. I assume ViewState may not work on this as the dynamically generated controls need to be in the page_load event. Please guide as this getting way more complicated than what I had ever thought of it to be.

SPUtility.TransferToErrorPage("My Message") not allowed to attach any controls event.

Hi, I have created a custom error page and update it using to webApplication using following code: WebApplication.UpdateMappedPage(SPWebApplicaton.SPCustomPage.Error, CustomErrorPage) My error page contains one link button and onClick event, I have to perform some operations. As I click on the button Error is occurred and onClick event code didn't execute. If I render custom error page by providing url in IE like http://myweburl/_layouts/myerrorpage then every thing is working fine i.e. every event is working fine. Also If I use SPUtility.Redirect() method instead of SPUtility.TransferToErrorPage() then also every thing is working fine. My error message is as follow in case of SPUtility.TransferToErrorPage(): Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that <machineKey> configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster. StackTrace is [HttpException (0x80004005): Unable to validate data.]    System.Web.Configuration.MachineKeySection.GetDecodedData(Byte[] buf, Byte[] modifier, Int32 start, Int32 length, Int32& dataLength) +10988853    System.Web.UI.ObjectStateFormatter.Deserialize(String inputString) +295 [ViewStateException: Invalid viewstate. Client IP: fe80::8960:150e:cf5d:2e17%11 Port: 53192 User-Agent: Mozill

Handling event from dynamically generated ImageButtons

Dear all,I have a situation here.Please review the following codeImports MySql.Data.MySqlClient Imports VB = Microsoft.VisualBasic Partial Class AddFriend Inherits System.Web.UI.Page Dim WithEvents btnAccept As ImageButton Dim WithEvents btnReject As ImageButton Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init Dim ConnectionString As String ConnectionString = ConfigurationManager.ConnectionStrings("MySqlConnectionString").ToString.Trim Dim MySqlConnection As New MySqlConnection(ConnectionString) Try MySqlConnection.Open() Dim MySqlCommand As New MySqlCommand("", MySqlConnection) MySqlCommand.CommandText = "Select `ccf`.uuid,`ccf`.requestmsg,`cu`.* from `chittochat`.`cc_friends` as `ccf`, `chittochat`.`cc_users` as `cu` where `cu`.uuid=`ccf`.uuid and `ccf`.fuuid='" & Membership.GetUser(Page.User.Identity.Name.Trim).ProviderUserKey.ToString & "' and `ccf`.accepted=0" Dim Reader As MySqlDataReader = MySqlCommand.ExecuteReader If Reader.HasRows Then Do While Reader.Read() Dim img As New Image With {.Height = 40, .Width = 35, .ImageUrl = "content\userphoto\" & Reader("PhotoURL").ToString.Trim & Reader("PhotoEXT"

change focus on controls in sharepoint list newform.aspx

hi all. i have newform.aspx where i hav required fields . when i say ok to enter the values the required field valiedates and shows error messages. but the problem is that the focus where it is suppose to get placed is promting in differnet place. can i change the focus of the controls inside newform.aspx or editform.aspx?jayaraja

Unexpected focus behaviour when disabling controls

I'm working with WindowsForms using C#, but I think the described control behaviour is language independent... I have a form containing 3 comboboxes A, B and C, which have the taborder A.TabIndex=0, B.TabIndex=1 and C.TabIndex=2. Combobox B is enabled/disabled depending on the content of A.Text in A's Validating event (A.Text = "dis" disables combobox B, A.Text="other" enables combobox B): private void A_Validating(object sender, CancelEventArgs e) {     if (A.Text == "dis") {         B.Enabled = false;     }     else {         B.Enabled = true;     } } The behaviour following then is very strange (executed exactly in the given order): 1.) I'm entering "dis" in combobox A. When pressing the tab key, the Validating event disables combobox B. Expected behaviour:  Focus is moved to combobox C Actual behaviour: Focus stays on combobox A 2.) I'm then entering "other" in combobox A and pressing the tab key. Expected behaviour:  Validating event is called and enables combobox B. Focus should then be on B. Actual behaviour: Validating event is NOT called, therefore B is still disabled. Focus is now on C. 3.) I'm setting the focus on combobox A (using tab key or mouse) and

Programmatically generated AsyncFileUpload does not fire UploadedComplete event


The AsyncFileUpload control turns green, indicating that the attachment was successfully uploaded, but the designated method for handling the server side UploadedComplete event is never executed.

using __doPostBack with dynamically generated controls


I'm making a page for dynamically handling surveys.  The questions and their related controls (multiple choice, text) are stored in a DB and fed into a page on loading.  For some questions, particular answers will need to disable other questions' controls as they are no longer valid in context.  For example, If the survey asks the user if they've worked in the past year and they respond "No" then I need to disable the choices for the "how much did you earn" question.  The tricky part is that I need to be able to undo this action as well.  If the user now selects "Yes" to the first question, I have to re-enable all the earnings choices.

There are too many controls to always trigger an event whenever something is clicked, so I'd like to limit my postbacks to only those option which can cause a skip to occur.  This becomes a problem for Radio Buttons and DropDown Lists, as I only want the selection/deselection of particular options to cause postback and the others to do nothing (though selection of such an "inert" option will cause postback if it causes the deselection of a skip-causing control).  Not having an equivalent "CheckedChanged" event for Radio Buttons as there is for Checkboxes is irritating.

My solution thus far (for Radio Buttons) is to add t

TextBox in UserControl: "TextChanged" event does not see other controls


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=&q

keep focus on textbox on textchange event



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

change attrib value in java script in dynamically generated controls


Hi all,

i use the below code to dynamically generate two dropdowns and a text box in my MVC project.

countValidate is used to concatenate and produce controls with postfix 1 ,2,3 etc.

now i need to access the Criteria? series dropdown and check their values and according to the values received on changing the Criteria dropdown the value textbox must be disabled or enabled, in javascript.

<% countValidate = 1;

<% foreach (var item in Model.ContactSearchCriteria)
               { %>
            <table width="100%">
                    <td width="30%">
                        <%= Html.DropDownList("Field" + countValidate, ViewData["SRFLD" + countValidate] as SelectList, "Select", new { @class = "selectTr

Setting focus on cell in datagrid after CollectionChanged event.




Having trouble setting the focus on a cell after the collection recieves a new row. This is my code:

 sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
			DataGridRowObjects<My_DataGridRow> oc = (DataGridRowObjects<My_DataGridRow>)sender;
 (e.Action == NotifyCollectionChangedAction.Add)
				//set focus to column 2 of the new row

				DataGridCell cell = my_datagrid.GetCell(e.NewStartingIndex, 2);
 (cell != null
				 DataGridCellInfo info = new
				 my_datagrid.CurrentCell = info;

Is there any event that fires after the CollectionChanged? My DataGridRow doesn't have a CellPresenter att this stage and GetCell fails. If I do the same with a button event instead, it works fine.

I just tried to add a dispatcher message instead but that did nothing:

Dispatcher.BeginInvoke(new Action(delegate()
  //set focus to column 2 of the new row
  DataGridCell c

Controls in a WPF UserControl don`t raise lost focus



I have a MainWindow with 3 main buttons at the top and below a MainUserControl.

In the MainUserControl I have at top 3 UserControls with ButtonBars and at the bottom a DataGrid.

When I enter data in a DataGridCell and I click into another cell a property change is fired in my ViewModel bound to the DataGrid.

When I enter data... and I click on one of the 3 main buttons again a property change is fired because of Lost Focus event.

When I ... and I click on one of the buttons in the ButtonBar in the UserControl no property change is fired because there seem to be no Lost Focus event.

How can I fix that?

How to disable the controls within the JQGrid on some other event



I am trying to disable the controls within the JQGrid on some other event. Please let me know how can i do this. Below is my JQGrid Basically i want to disable the custom buttons btnDeleteExistingRoles, btnAddExistingRoles and the checkboxes that are created in the "Select" column( i have written a custom formatter for this). Please help

jQuery(document).ready(function() {

    $('#btnHdnExistingRoles').click(function() {
        var lastsel2;
        jQuery("#grdExistingRoles").jqGrid({ url: '/SAPWebAccess/Role.mvc/GetExistingRoleForUser/',
            datatype: 'json', mtype: 'GET',
            colNames: ['Role ID', "<input type='checkbox' id = 'headerCheck' onclick='checkAll(\"grdExistingRole\");'>", 'Role Name', 'Role Text', 'Valid From'

How to create event handlers for Composite Controls



How to create event handlers for Composite Controls. I have created a composite control with label, textbox and button. Like this

        public TextBox txt1 = new TextBox();
        public Label lbl1 = new Label();
        public Button btn1 = new Button();

protected override void CreateChildControls()



Now how to write the code once a event fires like text changed or click.



ASP.NET validation controls are removing client event handlers.


 Below is a tiny section of code to highlight a problem that I am currently having. The textbox has an onblur event (the workings of the onblur event are irrelevant), and an associated RequiredFieldValidator. This code functions exactly as it should. However, if in the body onload event I simply raise an alert of the innerHTML of tr1 or td1, the onblur event does not appear (but it does work, and can be seen when I view source in IE7). If I remove the RequiredFieldValidator, the onblur event handler is shown in the alert, or if I retain the validator but change onblur to onfocus, then the event handler also appears in the alert. I need this to work as when the user increases the Quantity, duplicates of the table row are added (I have tried both cloneNode, and setting the innerHTML of each new table cell to that of the original, but as my alert proves, the onblur event handler is not included in what is copied). The same problem also occurs with onchange for select tags with validators. I am using Visual Studio 2008 (.Net 2), IE7 and IIS 7.

<tr id="tr1" /> 
  <td id="td1" />Quantity <input id="txtQuantity" onblur="fnBlur(this)" type="text" maxlength="2" value="1" runat="server" />   
 <asp:RequiredFieldValidator id="reqQuantity"
ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend