I think Marc and GraemeF's answers are great, but I'm going to add an answer (anyway) as an example of a slightly alternative approach. This approach reflects my "path of slack" :) programming philosophy. Note this example requires Linq.
My first goal would be to have a single variable of type TextBox available to hold the current active TextBox (or if that needed to be accessed from outside the Form, I'd make it accessible via a public property) : if I can get that, then I have an easy way to access the current active TextBox's current Text : just use the .Text property (no conversion required).
//on the Form where the TextBoxes are : make into a Public Property
// if you need to access this from outside the Form holding the TextBoxes
// a Form-level variable
private TextBox theActiveTB;
Then, on the Form, I'd make the Form Load event build a collection of the TextBoxes for me : and make sure they subscribed to the same 'KeyPress and 'Enter events :
// on the Form where the TextBoxes are : a Form-level variable
private List<TextBox> tbList;
// build the list of TextBoxes and set the same 'Enter event for each of them
// note the assumption that every TextBox on the Form is going to be handled
// in exactly the same way : probably better to isolate them in a Panel in case
// you have other TextBoxes for other purposes ; then you'd just use the same
// code here to enumerate all the TextBoxes in the Panel
private void Form1_Load(object sender, EventArgs e)
{
tbList =
(
from TextBox theTB in this.Controls.OfType<TextBox>()
select theTB
).ToList();
foreach (TextBox theTB in tbList)
{
theTB.KeyPress +=new KeyPressEventHandler(theTB_KeyPress);
theTB.Enter +=new EventHandler(theTB_Enter);
}
}
// so here's what the Enter event might look like :
private void theTB_Enter(object sender, EventArgs e)
{
theActiveTB = (TextBox)sender;
// reality check ...
// Console.WriteLine("entering : " + theActiveTB.Name);
}
// so here's what the KeyPress event might look like :
private void theTB_KeyPress(object sender, KeyPressEventArgs e)
{
// do what you need to do here
// access the Text in the Textbox via 'theActiveTB
// reality check
// Console.WriteLine(theActiveTB.Name + " : " + e.KeyChar );
}
Why bother to make List<TextBox> using Linq ? You could, after all, just loop through the Form (or a Panel, or whatever container) and check each control's type, and then, if it's a TextBox, assign the Event Handlers right on the spot. The reason why I chose to make a generic list of the TextBoxes is because : when I have a collection with a special shared identity, or purpose, or set of behaviors, it's often the case that I will want to do other things with its content as a "set" or "group."