我有两个带有文本框和标签的面板。我正在尝试使用panel1.texbox1 * panel2.textbox1 + panel1.textbox2 ...等等。但是当我运行程序时,它实际上显示了我所有文本框的产品。
这里我有创建文本框和标签的代码:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
int j,c=1;
int i = comboBox1.SelectedIndex;
if (i != null)
{
for (j = 0; j <= i; j++)
{
Label label = new Label();
label.Text = "w" + c;
label.Location = new System.Drawing.Point(5, 20 + (20 * c));
label.Size = new System.Drawing.Size(30, 20);
panel1.Controls.Add(label);
Label label2 = new Label();
label2.Text = "x" + c;
label2.Location = new System.Drawing.Point(5, 20 + (20 * c));
label2.Size = new System.Drawing.Size(30, 20);
panel3.Controls.Add(label2);
TextBox w = new TextBox();
w.Text = "";
w.Location = new System.Drawing.Point(35, 20 + (20 * c));
w.Size = new System.Drawing.Size(25, 20);
panel1.Controls.Add(w);
TextBox x = new TextBox();
x.Text = "";
x.Location = new System.Drawing.Point(35, 20 + (20 * c));
x.Size = new System.Drawing.Size(25, 20);
panel3.Controls.Add(x);
c++;
}
}
}
以下是我尝试使用的代码:
private void button4_Click(object sender, EventArgs e)
{
int suma = 0;
foreach (Control w1 in panel1.Controls.OfType<TextBox>())
{
foreach (Control w2 in panel3.Controls.OfType<TextBox>())
{
int textB1 = int.Parse(w1.Text);
int textB2 = int.Parse(w2.Text);
int textB3 = textB1 * textB2;
}
}
textBox3.Text = "" + suma;
}
答案 0 :(得分:0)
我还没有测试过代码,但这应该可以完成工作:
请注意,此代码不安全,您可能需要添加一些空值检查以使代码更具弹性
400ms
祝你好运!
答案 1 :(得分:0)
在您当前的代码中,您将所有控件(包括标签)转换为文本框,方法是对其进行public void pushTransferToStatus(Long id, Status status) {
// SOME PRECONDITIONS
switch (currentStatus) {
case OPEN:
// DO SOMETHING
break;
case SAVED:
// DO SOMETHING ASYNC
break;
case VALIDATED:
// DO SOMETHING
break;
case AWAITING_SHIPPING:
// DO SOMETHING
break;
case VERIFIED:
// DO SOMETHING
break;
case CLOSED:
// Exit case.
break;
default:
throw new UnsupportedOperationException();
}
pushTransferToStatus(id, newStatus);
}
,因为集合中还包含标签。
以下是我认为你应该做的事情:
OfType<TextBox>()
答案 2 :(得分:0)
您可以使用linq在一行中执行此操作,但您当然必须先在文本框中检查有效输入:
var panel1Texts = panel1.Controls.OfType<TextBox>().ToArray();
var panel2Texts = panel2.Controls.OfType<TextBox>().ToArray();
Func<TextBox, bool> isInvalid = (text) =>
{
int res;
return !int.TryParse(text.Text, out res);
};
var errorText = panel1Texts.FirstOrDefault(isInvalid);
if (errorText != null)
{
// Error handling
}
errorText = panel2Texts.FirstOrDefault(isInvalid);
if (errorText != null)
{
// Error handling
}
var sum = panel1Texts.Zip(panel2Texts, (tb1, tb2) => int.Parse(tb1.Text) * int.Parse(tb2.Text)).Sum();
textBox3.Text = sum.ToString();