check textbox focus

G

Guest

I have 2 textboxes and one button and I don't know why my code doesn't work.
All I'm trying to do is write a number 1 into the textbox with the focus. so
if the user puts the cursor in textBox1 and pushes the button the 1 should go
into that box. If the cursor is in the other one the 1 should go there. It
seems simple but doesn't work. Can anyone give me any hints? Here is the code:

private void button1_Click(object sender, System.EventArgs e)
{
if (textBox1.Focused == true)
textBox1.Text = "1";
if (textBox2.Focused == true)
textBox2.Text = "1";
}
 
A

ALI RAZA

Salam

Your code will not work correctly because when you click a Text Box, Focus
event is not fired, and as a result focus is false.

When you click on the TextBox, the Text Box Enter event is fired, here you
can set the focus of the text box by calling its Focus() Function. In this
way, ur code will work correctly


--
ALI RAZA SHAIKH
MCAD.net

www.programmersparadise.cjb.net
alirazashaikh.blogspot.com
 
C

Christian Stueben

Hi Orahm,
maybee i am wrong, but i would say that as soon as you klick on button1, the
button has the focus, So no one of your textboxes can have focus at that
moment.

To verify, add to your code:
if (button1.Focused == true) textbox1.Text = "b";
and try again. What happens?

greetings from germany
Chris
 
C

Christian Stueben

Hi Orahm,
i forgot to say...
you could use the .Leave-Event (is fired when focus leaves an element) to
let the textboxes write their number to some little helper variable. So the
button click can use the helper variable to determine which textbox had last
the focus.

Grettings from germany
Chris
 
G

Guest

Hi, thanks for replying. Both of your assumptions are correct. the focus is
always false because the button has it. Which event should I use to write the
one in the "last chosen" text box? I couldn't find an enter event?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top