在Datagridview中添加 [英] Addition in Datagridview

查看:66
本文介绍了在Datagridview中添加的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想添加Datagridview中存在的列式数据.如果所有值都存在于单元格中,我将得到总和.

如果单元格中的值不存在(NULL),则显示错误:
没有为Integer类型和DBNull类型定义

I want to add column wise data present in Datagridview. I am getting the sum if all values present in cells.

If in a cell value is not there(NULL) it is showing ERROR:

operator + is not defined for type Integer and type DBNull.


代码段:


Code snippet:

For j As Integer = 0 To DataGridView1.Columns.Count - 1
    For i As Integer = 0 To DataGridView1.Rows.Count - 1
        total = total + DataGridView1(j, i).Value
    Next

    TableLayoutPanel1.Controls(j).Text = total
    total = 0
Next

推荐答案

+运算符不适用于null,因此在添加之前先进行简单检查数据如下
+ operator does not work with null so put a simple check before adding the data as follow
For j As Integer = 0 To DataGridView1.Columns.Count - 1
    For i As Integer = 0 To DataGridView1.Rows.Count - 1
        if IsDBNull(DataGridView1(j, i).Value) <> True then
             total = total + DataGridView1(j, i).Value
        end if
    Next

    TableLayoutPanel1.Controls(j).Text = total
    total = 0
Next


原因是使用
The reason for this is that null values from the database are represented with DbNull[^] values in memory. You need to add a conditional around the place where you add DataGridView1(j, i).Value to the total, deciding what to do when you see a null value (for example, skip it). There is an example at the above link showing you how to do it.


尝试此操作
try This
total = total + If(IsDBNull(Me.DataGridView1.Item(j, i).Value), 0, Me.DataGridView1.Item(j, i).Value)


这篇关于在Datagridview中添加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆