简体   繁体   English

使用文本框数组将它们与按钮对应

[英]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. 我试图对左侧的所有按钮使用相同的click事件,为了做到这一点,我需要一种方法来根据被单击的按钮选择正确的textBox。 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. 您可以使用Button.Tag属性将按钮与相应的文本框“关联”。

// 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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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