[英]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();
}
我試圖對左側的所有按鈕使用相同的click事件,為了做到這一點,我需要一種方法來根據被單擊的按鈕選擇正確的textBox。 使用此代碼,單擊按鈕不會執行任何操作。
如果我告訴它打印名稱,則必須在文本框中打印正確的名稱。
提前致謝。
您可以使用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.