• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1766
  • Last Modified:

Focus () in the textbox

I have a textbox in a gridview. I'd like to set the focus() to the below text box of the next row when the user clicks "the "enter" key. How can I do this in C#?
0
jung1975
Asked:
jung1975
  • 14
  • 12
1 Solution
 
raterusCommented:
Probably going to be tough depending on your experience level,

you'll first have to use javascript, not C# as this is a client-side feature
second, you'll need add javascript to successfully catch and call a function when the user hits enter
third, you'll have to know for the textbox entered, what the id of the textbox below the current textbox is
lastly, you use javascript's setfocus method to move the cursor.

It is definitely possible, albeit..."fun"
0
 
jung1975Author Commented:
Ok, now I am trying to use tab key to navigate( go down) textboxes in a gridview.
I am using below code to save a record in a textbox(itememplate) in the gridview and use tab key ( table index) to move to the next text box of the below row. However, the problem is as soon as I hit the "Enter" key  , the focus() got disappeared. How can I keep the focus() after the postback? I want to keep the focus() in the current textbox , so I can move the focus() by using a tab key. thank you for your help.


 protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate)
        { if (e.Row.RowType == DataControlRowType.DataRow)
          {
                TextBox TX1 = ((TextBox)e.Row.Cells[13].FindControl("TextBox2"));
                TX1.Attributes.Add("onkeydown", "if(event.which || event.keyCode){if ((event.which == 13) || (event.keyCode == 13)) {document.getElementById('" + Button2.UniqueID + "').click();return false;}} else {return true}; ");
}
0
 
raterusCommented:
do you want to postback when the enterkey is pressed?  I'm sure you do, ok then, Is it easy enough to know which textbox was focused when the page is postedback?  You'll have to go into that row of the gridview, get a reference to the textbox and set the focus again.
0
Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

 
jung1975Author Commented:
yes, I want to save the record that entered into the textbox when the user hit the Enter key.


" get a reference to the textbox and set the focus again."
That's what I 've been trying to do ,but no luck so far..
Is there any way you can provide me some code example?  thank you
0
 
raterusCommented:
Have you looked into client-callbacks?  It would be pretty snazzy to go for that route instead of posting back the entire page just to save one little value.  Then the setfocus issue wouldn't be an issue since the page never posts back.
0
 
jung1975Author Commented:
yes, I have , but since I am new to asp.net. It's kind of hard to understand it and write code.

I am using a java script to be able to click the save button when the user press the Enter key.
Can I do the same thing by using client-callback? what do i need to change in my current code? can you show me some code example?


if (e.Row.RowType == DataControlRowType.DataRow && ((TextBox)e.Row.Cells[13].FindControl("TextBox2")).TabIndex == 1 )
          {  
               //((TextBox)e.Row.Cells[13].FindControl("TextBox2")).Attributes.Add("onkeydown", "doFocus(window.event.keyCode);");
                TextBox TX1 = ((TextBox)e.Row.Cells[13].FindControl("TextBox2"));
                TX1.Attributes.Add("onkeydown", "if(event.which || event.keyCode){if ((event.which == 13) || (event.keyCode == 13)) {document.getElementById('" + Button2.UniqueID + "').click();return false;}} else {return true}; ");
       
             
             
            }
0
 
raterusCommented:
Certainly you can use client-callbacks, and it would be a lot easier from the users perspective to use them.
However these aren't the easiest to setup.  and I haven't messed with them, or use C# enough to give you solid advice.  If you really want to go down this route, it's going to be some learning.

I can probably help you with the setfocus issue though,

If it is a button in the GridView Row, you should be able to catch the button click via the RowCommand event, then in that event you can do something like this

TextBox tx = (TextBox)myGridView.Rows[(int)e.CommandArgument].FindControl("txtBox"); //Excuse any syntax errors, I'm not fluent in C#!
tx.Focus();
0
 
jung1975Author Commented:
Actually the button is seperated from the gridview.. should i try it button_click event?
0
 
raterusCommented:
outside of the GridView ehh?  How do you know which row to save then?
0
 
jung1975Author Commented:
Actually, it saves all of rows, I know it's not a practical solution.

I just don;t want to lose the focus() whenever there is  postback for now..

    protected void Button2_Click(object sender, EventArgs e)
    {
        for (int i = 0; i < (GridView1.Rows.Count); i++)
        {
            GridViewRow row = GridView1.Rows[i];


            SqlDataSource1.UpdateParameters["Supp"].DefaultValue = ((TextBox)row.Cells[13].FindControl("TextBox2")).Text;
            SqlDataSource1.UpdateParameters["Medical"].DefaultValue = ((TextBox)row.Cells[12].FindControl("TextBox4")).Text;
            SqlDataSource1.UpdateParameters["Assertions_key"].DefaultValue = GridView1.DataKeys[i].Value.ToString();
            SqlDataSource1.Update();

            FormView1.DataBind();
            FormView2.DataBind();
           
            BDPUpdate();



        }
    }
0
 
raterusCommented:
Ok, here is what you need to do then,

Add a hiddenfield to your aspx page, somewhere outside of the GridView.

When you are adding the "onkeydown" attribute to the textbox, you need to add javascript to set this hiddenfield's value to the rowindex, that way when the page is posted back, the row index they were at is posted back with it.

Now I'm assuming when the page posts back and you save the data, you want to go to the next row, and focus that textbox.  In the button event, you will get the value of the hidden field (At worst you can use Request.Form["myHiddenFieldName"]), depending on the value, increment it by one, then go back to the GridView's rows collection, find the row, find the textbox, and focus it.

I see no reason this shouldn't work.
0
 
jung1975Author Commented:
thanks, I don't have to go to the next row I just want to keep the focus9) in that row, so I can go tot eh next row by using a tab key.

I think you idea is perfect for my situation. but, here i am again having a hard time to figure out how I am going to assagin the rowindex of that row to the hidden field ( let's say I create a label out side of a gridview).

Can you help me on writing the code?
0
 
raterusCommented:
I guess you'd first need to add this somewhere to your code

<input type="hidden" name="myHiddenField" id="myHiddenField" />

Then you'd modify this,

if (e.Row.RowType == DataControlRowType.DataRow && ((TextBox)e.Row.Cells[13].FindControl("TextBox2")).TabIndex == 1 )
          {  
               //((TextBox)e.Row.Cells[13].FindControl("TextBox2")).Attributes.Add("onkeydown", "doFocus(window.event.keyCode);");
                TextBox TX1 = ((TextBox)e.Row.Cells[13].FindControl("TextBox2"));
                TX1.Attributes.Add("onkeydown", "if(event.which || event.keyCode){if ((event.which == 13) || (event.keyCode == 13)) {document.getElementById('myHiddenField').value=" + e.Row.RowIndex.ToString() + ";document.getElementById('" + Button2.UniqueID + "').click();return false;}} else {return true}; ");
            }

Then you'd do something like this in the last event handler you shared,

    protected void Button2_Click(object sender, EventArgs e)
    {
        int currentRow = (int)Request.Form["myHiddenField"];
        for (int i = 0; i < (GridView1.Rows.Count); i++)
        {
            GridViewRow row = GridView1.Rows[i];

            if (i==currentRow){
              TextBox TX1 = ((TextBox)row.Cells[13].FindControl("TextBox2"));
              TX1.Focus();
            }

            SqlDataSource1.UpdateParameters["Supp"].DefaultValue = ((TextBox)row.Cells[13].FindControl("TextBox2")).Text;
            SqlDataSource1.UpdateParameters["Medical"].DefaultValue = ((TextBox)row.Cells[12].FindControl("TextBox4")).Text;
            SqlDataSource1.UpdateParameters["Assertions_key"].DefaultValue = GridView1.DataKeys[i].Value.ToString();
            SqlDataSource1.Update();

            FormView1.DataBind();
            FormView2.DataBind();
           
            BDPUpdate();



        }
    }

Again, excuse my syntax, I'm a bit rusty on C#!

0
 
jung1975Author Commented:
Ok..but it still not working

Is it becuase I am trying to save all values in the whole rows at the same time?
Here is my button click event:

protected void Button2_Click(object sender, EventArgs e)
{



for (int i = 0; i < (GridView1.Rows.Count); i++)
{
GridViewRow row = GridView1.Rows[i];


SqlDataSource1.UpdateParameters["Supp_contractual_Allowances"].DefaultValue = ((TextBox)row.Cells[13].FindControl("TextBox2")).Text;
SqlDataSource1.UpdateParameters["Medical"].DefaultValue = ((TextBox)row.Cells[12].FindControl("TextBox4")).Text;
SqlDataSource1.UpdateParameters["Assertions"].DefaultValue = GridView1.DataKeys[i].Value.ToString();
SqlDataSource1.Update();



}



}



}




If so, how can I get the reference of that row you just entered the data and save it to the database

How can I grap the index of that particualr row? so I don't have to save all values in the whole rows..

GridViewRow row = GridView1.Rows[0];


protected void Button2_Click(object sender, EventArgs e)
{

GridViewRow row = GridView1.Rows[0];


SqlDataSource1.UpdateParameters["Supp"].DefaultValue = ((TextBox)row.Cells[13].FindControl("TextBox2")).Text;
SqlDataSource1.UpdateParameters["Medical"].DefaultValue = ((TextBox)row.Cells[12].FindControl("TextBox4")).Text;
SqlDataSource1.UpdateParameters["Assertions_key"].DefaultValue = GridView1.DataKeys[i].Value.ToString();
SqlDataSource1.Update();



}

0
 
raterusCommented:
You don't look to be doing in the button's event what I suggested in the last example,

            if (i==currentRow){
              TextBox TX1 = ((TextBox)row.Cells[13].FindControl("TextBox2"));
              TX1.Focus();
            }
0
 
jung1975Author Commented:
I've tried as you suggested, but it still not working. the focus is disappeared...

  protected void Button2_Click(object sender, EventArgs e)
    {
        int currentRow = myHiddenField.value;

        for (int i = 0; i < (GridView1.Rows.Count); i++)
        {
            GridViewRow row = GridView1.Rows[i];

            if (i==currentRow){
              TextBox TX1 = ((TextBox)row.Cells[13].FindControl("TextBox2"));
              TX1.Focus();
            }

            SqlDataSource1.UpdateParameters["Supp"].DefaultValue = ((TextBox)row.Cells[13].FindControl("TextBox2")).Text;
            SqlDataSource1.UpdateParameters["Medical"].DefaultValue = ((TextBox)row.Cells[12].FindControl("TextBox4")).Text;
            SqlDataSource1.UpdateParameters["Assertions_key"].DefaultValue = GridView1.DataKeys[i].Value.ToString();
            SqlDataSource1.Update();

            FormView1.DataBind();
            FormView2.DataBind();
           
            BDPUpdate();



        }
    }
0
 
raterusCommented:
#1, do you understand my solution enough to know why it will work?
#2, If the answer to #1 is yes, can you debug your code and see where the problem lies?

I'd be shooting in the wind to try and guess why it isn't working now.
0
 
jung1975Author Commented:



yes, I do. I've debuged the code.. I am keep getting an error says: Object reference not set to an instance of an object.
 "SqlDataSource1.UpdateParameters["Supp"].DefaultValue = ((TextBox)row.Cells[13].FindControl("TextBox2")).Text; "

and it loooks like the reson it doesn't wotk is because it trying to save values in the all rows ( by looping through the each row), so the foucus is set to the end of the row by the end of updting process everytime there is a postback. I am not 100% sure my guess is correct though..

If I can figure out how I can grap the row index of that particular textbox (inside of button clcik event ) , and update only the value of that text box which  I just entered the value and set back the focus () to that particular textbox...


Waht do you think?
0
 
raterusCommented:
Ok, I see you are using the SqlDataSource Controls, I'm not too familiar with those yet.  If you think my additon to the button click is breaking something, by all means, take it out and do it like this!

        for (int i = 0; i < (GridView1.Rows.Count); i++)
        {
            GridViewRow row = GridView1.Rows[i];

            SqlDataSource1.UpdateParameters["Supp"].DefaultValue = ((TextBox)row.Cells[13].FindControl("TextBox2")).Text;
            SqlDataSource1.UpdateParameters["Medical"].DefaultValue = ((TextBox)row.Cells[12].FindControl("TextBox4")).Text;
            SqlDataSource1.UpdateParameters["Assertions_key"].DefaultValue = GridView1.DataKeys[i].Value.ToString();
            SqlDataSource1.Update();

            FormView1.DataBind();
            FormView2.DataBind();
           
            BDPUpdate();
        }

        // now focus the textbox

        for (int i = 0; i < (GridView1.Rows.Count); i++)
        {
            if (i==currentRow){
              TextBox TX1 = (TextBox)row.Cells[13].FindControl("TextBox2"); // Make sure this is the textbox you are really trying to focus on!!
              TX1.Focus();
            }
        }
0
 
jung1975Author Commented:
sorry, but same thing..

I am getting an error says: NullReferenceException was unhandled by user code" "Object reference not set to an instance of an object"  
            SqlDataSource1.UpdateParameters["Supp"].DefaultValue = ((TextBox)row.Cells[13].FindControl("TextBox2")).Text;


0
 
jung1975Author Commented:
Actually I figured it out the error issue, but still not get the focus ... it just disappeared
0
 
raterusCommented:
When you say disappeared, I don't know what you mean.  I'd set a breakpoint on that line and see if it is even running.  I'd also make sure your hidden field has a proper value in it.  This  process could break anywhere you see...
0
 
jung1975Author Commented:
what I meatn is the focus9) is goes. I don't see it anymore in the textbox.
yes, the hiddenfield is storing the right row index value. I really don;t know what is wrong here...
Really frustrating...
0
 
raterusCommented:
But does this line ever run?

              TX1.Focus();
0
 
jung1975Author Commented:
Thanks, I think I figured it out. I put it in to Gridvie_prerender event..see the below code.
I have one more problem though. I'd like to figure out whether I shoudle set the focus() to textbox2 or textbox4  based on the tabindex ,but it looks like it always set to value = 0.. I am not sure why?

I am trying to store the tabindex value to another hidden field and use that value to determine where I should set the focus() to Textbox2 or Textbox4 based after the postback....



protected void GridView1_PreRender(object sender, EventArgs e)
    {
       
       
        if (this._fEditGridView1 )
        {
            int currentRow = Convert.ToInt32(myHiddenField.Value);
            int tabindex1 = Convert.ToInt32(myHiddenField1.Value);
            for (int i = 0; i < (GridView1.Rows.Count); i++)
            {
                GridViewRow row = GridView1.Rows[i];

                if (i == currentRow && tabindex1==1)
                {
                    TextBox TX1 = ((TextBox)row.Cells[13].FindControl("TextBox2"));
                    TX1.Attributes.Add("onfocus", "this.select()");
                    TX1.Focus();
                   
                }

                if (i == currentRow && tabindex1 == 0)
                {
                    TextBox TX2 = ((TextBox)row.Cells[12].FindControl("TextBox4"));
                    TX2.Attributes.Add("onfocus", "this.select()");
                    TX2.Focus();

                }
            }

        }


       
    }


protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
     
     
         if (e.Row.RowType == DataControlRowType.DataRow && ((TextBox)e.Row.Cells[13].FindControl("TextBox2")).TabIndex == 1 )
          {
                TextBox TX1 = ((TextBox)e.Row.Cells[13].FindControl("TextBox2"));

                TX1.Attributes.Add("onkeypress", "if(event.which || event.keyCode){if ((event.which == 13) || (event.keyCode == 13)) {document.getElementById('myHiddenField').value=" + e.Row.RowIndex.ToString() + ";document.getElementById('myHiddenField1').value=" + e.Row.TabIndex.ToString() + ";document.getElementById('" + Button2.UniqueID + "').click();return false;}} else {return true}; ");
            }
       
   


               if (e.Row.RowType == DataControlRowType.DataRow && ((TextBox)e.Row.Cells[12].FindControl("TextBox4")).TabIndex == 0)
            {


                TextBox TX2 = ((TextBox)e.Row.Cells[12].FindControl("TextBox4"));
                TX2.Attributes.Add("onkeypress", "if(event.which || event.keyCode){if ((event.which == 13) || (event.keyCode == 13)) {document.getElementById('myHiddenField').value=" + e.Row.RowIndex.ToString() + ";document.getElementById('myHiddenField1').value=" + e.Row.TabIndex.ToString() + ";document.getElementById('" + Button2.UniqueID + "').click();return false;}} else {return true}; ");
               
            }


           int tabindex = GridView1.TabIndex;
             
       
    }
     
0
 
jung1975Author Commented:
I figured it out!!!!! finally.

I really apprecialte allof your help...   thank you again.
0

Featured Post

Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

  • 14
  • 12
Tackle projects and never again get stuck behind a technical roadblock.
Join Now