Reputation: 125
I have a column of 10 textBoxs and another column of 10 labels. I want each Label
to be the product between the TextBox
at its left and a constant K (when the TextBox
is completed).
I was thinking a way to write one function to handle all events of textBoxs Leave
, and change the associated label.
Is there an easy way to know which Label
to change without comparing the sender with each TextBoxt
?
I hope I made myself understood, thanks in advance
Upvotes: 1
Views: 70
Reputation: 390
Make new object that contained of 1 TextBox and 1 Lable Write all of function and handler in this new object Use this new object in your project instead of standard TextBox and Lable Each of them work separately and do not need to write add any control code to them
Upvotes: 1
Reputation: 117084
I'd use a couple of arrays and do this:
var labels = new[] { label1, label2, label3, label4, label5, label6, label7, label8, label9, label10, };
var textBoxes = new[] { textBox1, textBox2, textBox3, textBox4, textBox5, textBox6, textBox7, textBox8, textBox9, textBox10, };
for (int i = 0; i < 10; i++)
{
var textBox = textBoxes[i];
var label = labels[i];
textBox.Leave += (_s, _e) => label.Text = (double.Parse(textBox.Text) * 3.14159).ToString();
}
Upvotes: 1
Reputation: 125217
Using TableLayoutPanel
Use a TableLayoutPanel
, add all the text boxes to the first column and all the labels to the second column. Then handle Validating
event of all text boxes using a single event handler.
const int K = 10;
private void TextBoxes_Validating(object sender, System.ComponentModel.CancelEventArgs e)
{
var txt = (TextBox)sender;
if (int.TryParse(txt.Text, out int value))
{
var row = tableLayoutPanel1.GetRow(txt);
var lbl = tableLayoutPanel1.GetControlFromPosition(1, row);
lbl.Text = $"{value * K}";
}
}
You can use TableLayoutPanel
methods to find controls based on the position and also find position of a control using GetRow
, GetColumn
, GetPositionFromControl
, GetControlFromPosition
.
Using DataGridView
Another option would be using a DataGridView
control bound to a DataTable
. The DataTable
can have an int column and an expression column.
const int K = 10;
private void Form1_Load(object sender, EventArgs e)
{
var dt = new DataTable();
dt.Columns.Add("C1", typeof(int));
dt.Columns.Add("C2", typeof(int), $"C1 * {K}");
dt.Rows.Add(1);
dt.Rows.Add(2);
dt.Rows.Add(3);
dataGridView1.DataSource = dt;
}
To learn about expression format take a look at DataColumn.Expression
.
Upvotes: 1
Reputation: 514
give all of them a common class. create a javascript handler for it and use $(this) to access the particular textbox on event. to access label you could use .Closest() function.
Upvotes: 0