Reputation: 3
I have 12 textboxes and 12 labels inside a GroupBox.
When a price is entered into any of the textboxes, I want the tax to be calculated and then shown in label next to this textbox.
I have written code to calculate the tax, but it's visible only in the first label labelTax01
.
My code listing is as follows:
public void Form1_Load(object sender, EventArgs e)
{
foreach (Control ctrl in groupBoxPrice.Controls)
{
if (ctrl is TextBox)
{
TextBox price= (TextBox)ctrl;
price.TextChanged += new EventHandler(groupBoxPrice_TextChanged);
}
}
}
void groupBoxPrice_TextChanged(object sender, EventArgs e)
{
double output = 0;
TextBox price= (TextBox)sender;
if (!double.TryParse(price.Text, out output))
{
MessageBox.Show("Some Error");
return;
}
else
{
Tax tax = new Tax(price.Text); // tax object
tax.countTax(price.Text); // count tax
labelTax01.Text = (tax.Tax); // ***help*** ///
}
}
Upvotes: 0
Views: 293
Reputation: 216353
Name your labels (for example LabelForPrice001, LabelForPrice002, etc...), then insert this name in the Tag property of each price textbox at desing time.
At this point finding the textbox means also finding the associated label with a simple search in the Controls collection of the groupBox....
By the way, you will find very useful, to simplify your loops, the extension OfType
public void Form1_Load(object sender, EventArgs e)
{
foreach (TextBox price in groupBoxPrice.Controls.OfType<TextBox>())
{
price.TextChanged += new EventHandler(groupBoxPrice_TextChanged);
}
}
void groupBoxPrice_TextChanged(object sender, EventArgs e)
{
double output = 0;
TextBox price= (TextBox)sender;
if(!double.TryParse(price.Text, out output))
{
MessageBox.Show("Some Error");
return;
}
else
{
Tax tax = new Tax(price.Text);
tax.countTax(price.Text);
// retrieve the name of the associated label...
string labelName = price.Tag.ToString()
// Search the Controls collection for a control of type Label
// whose name matches the Tag property set at design time on
// each textbox for the price input
Label l = groupBoxPrice.Controls
.OfType<Label>()
.FirstOrDefault(x => x.Name == labelName);
if(l != null)
l.Text = (tax.Tax);
}
}
Upvotes: 3