如果不是IsDBNull,则将Date列转换为字符串/标签

时间:2014-05-16 15:23:37

标签: vb.net date-conversion

我正在尝试(太长时间)将DateTime列转换为label.Text。

各种错误:

我错过了什么?

drExpDatesRow = dtAllCompanies.Select("CompanyID = " + CompanyID.ToString())

    Dim ls_ExpiresDateString As String
    If (Not IsDBNull(drExpDatesRow("Expdate"))) Then
        Date.TryParse(drExpDatesRow("Expdate").ToString(), ls_ExpiresDateString)
        'ls_ExpiresDateString = ldt_ExpiresDate.ToString("MM/dd/yyyy")
        lbl_ExpireDate.Text = ls_ExpiresDateString.ToString()
    Else
        lbl_ExpireDate.Text = ""
    End If
  

System.InvalidCastException未处理Message = Conversion from   字符串“Expdate”键入'Integer'无效   Source = Microsoft.VisualBasic StackTrace:          在Microsoft.VisualBasic.CompilerServices.Conversions.ToInteger(String   值)          在C:\ inetpub \ zzz.vb中的zzz.winCompanyInfo.CompanyInfo_Load(Object sender,EventArgs e):第638行          在System.Windows.Forms.Form.OnLoad(EventArgs e)          在System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible)          在System.Windows.Forms.Control.CreateControl()          在System.Windows.Forms.Control.WmShowWindow(消息& m)          在System.Windows.Forms.Control.WndProc(消息& m)          在System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)          在System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd,Int32 msg,IntPtr wparam,IntPtr lparam)InnerException:   System.FormatException          消息=输入字符串格式不正确。          来源= Microsoft.VisualBasic程序          堆栈跟踪:               在Microsoft.VisualBasic.CompilerServices.Conversions.ParseDouble(String   Value,NumberFormatInfo NumberFormat)               在Microsoft.VisualBasic.CompilerServices.Conversions.ToInteger(String   值)          的InnerException:

更新**添加了DataRow逻辑

2 个答案:

答案 0 :(得分:2)

使用TryParse时,请使用相同的数据类型。

Dim drExpDatesRow = (From dr As DataRow In dtAllCompanies.Rows 
                     Where dr("CompanyId").ToString =
                     CompanyID.ToString).FirstOrDefault

Dim ls_ExpiresDate As Date      ' Date not String
If (Not drExpDatesRow Is Nothing) Then
  If Date.TryParse(drExpDatesRow("Expdate").ToString(), ls_ExpiresDate)
    lbl_ExpireDate.Text = ls_ExpiresDate.ToString()
  End If
Else
    lbl_ExpireDate.Text = ""
End If

答案 1 :(得分:1)

您的代码中存在多个问题。这个应该好好处理好事情

drExpDatesRow = dtAllCompanies.Select("CompanyID = " + CompanyID.ToString()) ' returns array

lbl_ExpireDate.Text = ""
If drExpDatesRow.Length > 0 Then

    If (Not IsDBNull(drExpDatesRow(0)("Expdate"))) Then

        Dim myDate As DateTime
        Dim res As Boolean = Date.TryParse(drExpDatesRow("Expdate"), myDate)

        If res Then lbl_ExpireDate.Text = MyDate.ToString("<format>")
    End If
End If