简体   繁体   中英

Using TextBox Array to Correspond them with a Button

private void button1_Click(object sender, EventArgs e)
    {
         TextBox[] allTextBoxs = { textBox2, textBox3, textBox4, textBox5 };

         Button buttonNum = sender as Button;
         String Num = buttonNum.Name;

         var getNumbers = (from t in Num
                           where char.IsDigit(t)
                           select t).ToArray();
         string Test = new string(getNumbers);
         int Number = (Convert.ToInt32(Test));

        String theName = ("textBox" + Number.ToString());
        TextBox textBoxNum = allTextBoxs[Number];

        buttonLogic(textBoxNum);
    }

private void buttonLogic(TextBox textBoxNum)
    {
        decimal price = 0;

        if (String.IsNullOrEmpty(textBoxNum.Text))
        {
            textBoxNum.Text = "0";
        }

        if (!decimal.TryParse(textBoxNum.Text, out price))
        {
            textBoxNum.Text = "0";
        }

        price = Convert.ToDecimal(textBoxNum.Text);
        sum = sum + price;
        textBox1.Text = sum.ToString();
        calculateTotal();
        calculateChange();
    }

This is the complete form without the broken code

I am trying to use the same click event for all the buttons on the left and in order to do that I need a way to select the right textBox according to the button that was clicked. With this code, the buttons do nothing when clicked.

If I tell it to print the name it has to a textbox it prints the correct name.

Thanks in advance.

You can "associate" buttons with correspondent textboxes by using Button.Tag property.

// In Constructor

button1.Tag = textbox1;
button1.Click += AllButtons_Click;

button2.Tag = textbox2;
button2.Click += AllButtons_Click;


// Then you can access textboxex from the event handler
private void AllButtons_Click(object sender, EventArgs e)
{
    var button = (Button)sender;
    var textbox = (TextBox)button.Tag;

    buttonLogic(textbox);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM