Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Shaun E on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

c# Insert Text into Textbox

Status
Not open for further replies.

danielkelly

IS-IT--Management
Aug 13, 2006
28
AU
I have a series of textboxes on a Windows Form and a Series of buttons aswell. What I am trying to achieve sounds quite simple but I cannot figure out how to do it. Basically all Im trying to achieve is each button has some predefined text associated with it and when the user clicks the button, it inserts that text into the textbox which has the focus. The problem with this is that when you click on the button you lose the focus from the Textbox. The only way I have figured out is to save which control has focus before the button is clicked. This works but when you have 32 textboxes on a form, surely there is a better way than creating an On_Enter Method or similar to set the value of the Control which needs the text.

Any help would be muchly appreciated
 
why not create a routine the takes in the name of the text box and then set focus on the control. You would call this routine after you enter the text in the text box

Code Example
Code:
TextBox tb1 = new TextBox
TextBox tb2 = new TextBox

private void Button1_Click(object sender, EventArgs e)
{
 tb1.text "whatever";
 GiveControlFocus(tb1)
}

private void Button2_Click(object sender, EventArgs e)
{
 tb2.text "whatever";
 GiveControlFocus(tb2)
}

private void GiveControlFocus(TextBox tb)
{
 tb.Focus
}

Does that help?
 
The problem is I dont know which textbox has the focus. For example I want to click on TextBox13,, type some info and then press the Button1 to insert some text into Textbox13, however I may want to do the same thing with Button2.
 
How about trying the following:

Code:
 public partial class Form1: Form
   {
      public TextBox objectFocus;

      public Form1()
      {
         InitializeComponent();
      }

      private void textBox_Enter( object sender, EventArgs e )
      {
         objectFocus = (TextBox)sender;
      }

      private void button1_Click( object sender, EventArgs e )
      {
         objectFocus.Text += "button1";
      }

      private void button2_Click( object sender, EventArgs e )
      {
         objectFocus.Text += "button2";
      }
   }

Select all the textboxes together, and from the properties, set the Enter event to textbox_Enter.

Hope that helped
Regards
Andrew

ABC -
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top