首先,我强烈建议使用.NET方法,而不是旧的VB方法。我通常会将OPTION STRICT
设置为On
,这样可以避免运行时为您完成的“神奇”转换。相反,您必须指定正确的类型,这是一件好事,因为它可以防止运行时错误,并且还有助于学习.NET类型和方法。
我会将这些文本框全部添加到相同的容器控件(如Panel
或类似的东西)。我还建议为您的控件使用更有意义的名称(f.e。TxtTotal
用于全文本框)。
所以,如果所有的价格文本框的名字与TxtPrice
(FE TxtPrice1
等)和所有数量,文本框启动开始TxtQuantity
(FE TxtQuantity1
等),这LINQ查询方法将工作:
Dim allTextBoxes = PriceQuantityPanel.Controls.OfType(Of TextBox)()
Dim allPrices = From txt In allTextBoxes
Where txt.Name.StartsWith("TxtPrice")
Dim allQuantities = From txt In allTextBoxes
Where txt.Name.StartsWith("TxtQuantity")
Dim price As Decimal
Dim invalidPrices = From txt In allPrices
Where Not Decimal.TryParse(txt.Text, price)
If invalidPrices.Any() Then
MessageBox.Show("Please enter valid prices(Decimal)!")
Return
End If
Dim quantity As Int32
Dim invalidQuantities = From txt In allQuantities
Where Not Int32.TryParse(txt.Text, quantity)
If invalidQuantities.Any() Then
MessageBox.Show("Please enter valid quantities(Integer)!")
Return
End If
现在你可以通过数字后缀“加入”价格和数量文本框对:
Dim query = From txtP In allPrices
Join txtQ In allQuantities
On txtP.Name.Substring("TxtPrice".Length) Equals txtQ.Name.Substring("TxtQuantity".Length)
Select New With {.Price = Decimal.Parse(txtP.Text), .Quantity = Int32.Parse(txtQ.Text)}
Dim totalSum As Decimal = query.Sum(Function(x) x.Price * x.Quantity)
TxtTotal.Text = totalSum.ToString()
改为使用“列表”,并存储您的文本框值。然后在'foreach'中使用该列表进行计算。 –
Rahul
2014-10-02 12:01:27
要开始以一种易于理解的方式命名您的文本框:I.E.产品2etc的txtTotal1,txtQuantity1,txtPrice1等... – Steve 2014-10-02 12:01:30