vipin katiyar
vipin katiyar

Reputation: 3547

How do I enter the text in the specific textbox using button click

I am working on a WinForms application. There are four text boxes and one button in my form. I am using textBox1.SelectedText += "any string" on a button click so it writes to the first TextBox. If I add textBox1.SelectedText += "any string." then it writes both the textbox1 and textbox 2.

When I click textbox1 and press button then the sting only writes in the first textbox, and I click the second textbox and press the button then it write into second text box .Is there is any way to do this?

I'm using the following code.

private void button1_Click(object sender, EventArgs e)
{
    textBox1.SelectedText += "abc";
    textBox2.SelectedText += "abc";          
}

When I focus on the control, and when we press the button focus goes to the button. So how can we the focus on the one of the text boxes of my form after pressing the button?

Upvotes: 2

Views: 10409

Answers (2)

JKhuang
JKhuang

Reputation: 1553

You can take sample as below, hope this will give you muse.

 public partial class Form7 : Form
 {
    private TextBox textBox = null;
    public Form7()
    {
        InitializeComponent();

        // Binding to custom event process function GetF.
        this.textBox1.GotFocus += new EventHandler(GetF);
        this.textBox2.GotFocus += new EventHandler(GetF);
    }

    private void GetF(object sender, EventArgs e)
    {
        // Keeps you selecting textbox object reference.
        textBox = sender as TextBox;

    }

    private void button1_Click(object sender, EventArgs e)
    {
        // Changes you text box text.
        if (textbox != null) textBox.SelectedText += "You text";
    }
}

Upvotes: 2

Marco
Marco

Reputation: 57573

You can try this

    TextBox selTB = null;

    public Form1()
    {
        InitializeComponent();
        textBox1.Enter += tb_Enter;
        textBox2.Enter += tb_Enter;
        textBox3.Enter += tb_Enter;
        textBox4.Enter += tb_Enter;
    }

    ~Form1()
    {
        textBox1.Enter -= tb_Enter;
        textBox2.Enter -= tb_Enter;
        textBox3.Enter -= tb_Enter;
        textBox4.Enter -= tb_Enter;
    }

    private void tb_Enter(object sender, EventArgs e)
    {
        selTB = (TextBox)sender;
    }


    private void button1_Click(object sender, EventArgs e)
    {
        // Do what you need
        selTB.SelectedText += "abc";

        // Focus last selected textbox
        if (selTB != null) selTB.Focus();
    }

The idea is that when you enter a textbox, you store it in selTB.
So whan you click button, you know which one textbox was the last selected one.

Upvotes: 2

Related Questions