0

enter image description here

I am trying to fill two text box in a form using button controls but it seems to work for 1 only. when I run the program, I can't select between two text box. what condition should I use?

private void Button0_Click(object sender, EventArgs e)
{
    if (???????????????????)
    {
        metroTextBoxQuantity.Text = metroTextBoxQuantity.Text + "0";
    }
    else
    {
        metroTextBoxItemcode.Text = metroTextBoxItemcode.Text + "0";
    }
}
LarsTech
  • 80,625
  • 14
  • 153
  • 225

1 Answers1

0

One possible solution is to create a Control variable that stores a reference to the last clicked textbox. This would be handled by the Click event for both textboxes. Then, in your number button clicks, just append the number to the selected textbox variable. Something like this:

Control SelectedTextbox { get; set; } = null;

//Use this event handler for both the Quantity and Itemcode textbox
public TextBox_Click(object sender, EventArgs e)
{
    SelectedTextbox = (Control)sender;
}

private void Button0_Click(object sender, EventArgs e)
{
    if(SelectedTextbox == null)
        throw new Exception("SelectedTextbox has not been set");
    SelectedTextbox.Text += "0";
}

Note, if MetroTextBox doesn't inherit from Control, you'll need to change SelectedTextbox to a different type. It most likely does though.

You also may want to consider using a single event handler for all the button clicks instead of one for each. You can either parse what number button was clicked using the sender's name, or you can store the number of the button in the button's Tag and read it from there. But that's best left for another question.

Patrick Tucci
  • 1,824
  • 1
  • 16
  • 22