VB.NET 如何从 Form_Load 事件对 datagridview 中的某些列进行计算
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28467419/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
VB.NET How do I make calculation on some columns in datagridview from Form_Load event
提问by Essa
I'm newbie in vb.net and the forum , which I learned Much from it, I have a data importing from xml file to datagridview automaticly in the form load event , now I need a way to make calculation on some columns also in the form load event ,I dont want do it by cell changed or Cell End Edit event like this code I have:
我是 vb.net 和论坛的新手,我从中学到了很多,我在表单加载事件中有一个从 xml 文件自动导入到 datagridview 的数据,现在我需要一种方法来对某些列进行计算也在表单加载事件,我不想通过更改单元格或单元格结束编辑事件来完成,我有这样的代码:
Private Sub DataGridView1_CellEndEdit(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellEndEdit
Try
Dim order As DataGridView = DirectCast(sender, DataGridView)
If IsDBNull(order(0, e.RowIndex).Value) Then Exit Sub
order("column name", e.RowIndex).Value = order("column name", e.RowIndex).Value * textboxvalue.Text
Catch ex As Exception
End Try
End Sub
It work fine but I have to click each cell and tab out to see the result !! Not good way for many cells to click !
它工作正常,但我必须单击每个单元格并使用标签查看结果!许多单元格点击的好方法!
What is the best way of doing this? Thanks In advance
这样做的最佳方法是什么?提前致谢
回答by OneFineDay
This example would add the first two columns. If you cannot guaranty them to be valid Integers then Integer.TryParsewould be better. You can use other DataTypes like Singleor Doubleas needed.
此示例将添加前两列。如果你不能保证它们是有效的整数,那就Integer.TryParse更好了。您可以像Single或Double根据需要使用其他数据类型。
For Each row As DataGridViewRow In dgv.Rows
Dim total As Integer = Integer.Parse(row.Cells(0).Value) + Integer.Parse(row.Cells(1).Value)
Next
回答by Essa
Thanks To OneFineDay I'd figured out the solution :
感谢 OneFineDay 我找到了解决方案:
For Each row As DataGridViewRow In DataGridView1.Rows
row.Cells("column name").Value = row.Cells("column name").Value * textboxValue.Text
Next
Now I can calculate the desired column values by inserting its name .. Thank You again OneFineDay for your appreciated help .
现在我可以通过插入其名称来计算所需的列值.. 再次感谢 OneFineDay 的感谢帮助。

