2016-04-25 67 views
0

的代码:为什么0,而不是在VB System.Data.DataTable没有

 Private m_log_dataTable As System.Data.DataTable = Nothing 
     Private m_freq As String = Nothing 
     Private m_r As Single = Nothing 
     Private m_l As Single = Nothing 
     Private m_c As Single = Nothing 
     Private m_rp As Single = Nothing 
     Private m_rs As Single = Nothing 
     Private m_z As Single = Nothing 
     Private m_esr As Single = Nothing 
     Private m_dcr As Single = Nothing 
     Private m_q As Single = Nothing 
     Private m_d As Single = Nothing 

...

Private Sub LOG() 
     Try 
      m_freq = Nothing 
      m_r = Nothing 
      m_l = Nothing 
      m_c = Nothing 
      m_rp = Nothing 
      m_rs = Nothing 
      m_z = Nothing 
      m_esr = Nothing 
      m_dcr = Nothing 
      m_q = Nothing 
      m_d = Nothing 
      m_value = Nothing 
      m_unit = Nothing 
      m_log_dataTable.Rows.Add(DateTime.Now, getDUT(), getMode(), m_freq, m_r, m_l, m_c, m_r, m_rs, m_z, m_esr, m_dcr, m_q, m_d)'Line1 
      m_log_dataTable.Rows.Add(DateTime.Now, getDUT(), getMode(), Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing)'Line2 
     Catch ex As Exception 
      MsgBox("Exception when logging:" + ex.Message) 
     End Try 
    End Sub 

输出: enter image description here

为什么LINE-1(在上面代码)写0到数据表而不是Nothing? 我该怎么办?

谢谢

+0

这是编译吗? 'Private m_r As Single = Nothing'是将Nothing分配给单个变量(不是单个变量?) –

+0

@The_Black_Smurf是 – BAE

+0

@The_Black_Smurf - 这是VB.NET允许的。它和C#默认的一样(System.Single)' –

回答

2

您需要使用Nullable type。将所有single类型更改为single?并再次尝试。

Private m_r As Single? = Nothing 
Private m_l As Single? = Nothing 

// etc 

作为的Gabor评论,你需要访问Value财产或可用来Nullable(Of T)其他方法之一。

m_r.Value     ' Access the underlying value 

m_r.GetValueOrDefault() ' Underlying value or, if none, default for the underlying type 

m_r.GetValueOrDefault(3) ' Underlying value or, if none, some default value you decide 
+1

VB.NET中的'Nothing'等于C#中的'default(T)'(而不是'null')。 – Gabor

+0

我得到了“可为空的变量必须有一个值”的异常 – BAE

+1

我假设你调用了'm_log_dataTable.Rows.Add()'方法并引用了例如'm_freq.Value'而不是'm_freq'。或者试图将Value属性分配给Nullable实例的地方,例如'm_something = m_otherthing.Value' – Gabor

3

在VB.NET Nothing等于default(T)在C#(而不是null)。值类型不能为null,因此在db中,它们用not null约束列表示。

你确实应该使用Nullable(Of Single)(与相同)。

但当然这还不够。您应该修改数据库中的列,以便它们将具有null约束,而不是not null,并且System.Data.DataTable应该以相同的方式进行配置。

0

因为Single的默认值为0.您可以使用字符串列,也可以定义目标datagridview的列。

DataGridViewCellStyle1.Format = "N" 
Column1.DefaultCellStyle = DataGridViewCellStyle1 
相关问题