将 SQL 数据绑定数据表单元格转换为带 2 位小数的字符串,VB.net

Convert SQL databound datatable cell to string with 2 decimal places, VB.net

我目前在使用 SQL 服务器后端的 Microsoft Visual Studio Express 2013 中工作。我正在使用 SQL 查询来提取数据表,然后选择要从中提取数字的第一个单元格。我需要从数据表中取出这个数字,然后更改标签以将此数字显示为 2 位小数或百分比会更好。这是我的代码:

    Try
        Dim Associates As Integer = NUPAssociates.Value
        Dim Hours As Integer = NUPHours.Value
        Dim WorkingHours As Integer = (Associates * Hours)
        ' MsgBox(WorkingHours)
        'sql connection
        Using conn1 As New SqlConnection(connstring)
            conn1.Open()
            Using comm1 As New SqlCommand("SELECT ((sum([Time])/60)/@WorkHours) as EarnedHours FROM table1 " _
                                              & "Left Join table2 on table1.PartNumber + '-' = table2.PART_NUMBER " _
                                              & "WHERE col1  >= @start AND col1 < dateadd(day, 1, @Start) " _
                                              & "AND col2 = 25 AND col3 = 1 AND FloorNumber is not null and col4 > 30", conn1)
                comm1.Parameters.AddWithValue("@Start", DTPStart.Value.ToString("yyyy-MM-dd"))
                comm1.Parameters.AddWithValue("@WorkHours", WorkingHours)
                Dim dt As New DataTable
                Dim sql As New SqlDataAdapter(comm1)
                sql.Fill(dt)
                Dim EFF As String = dt.Rows(0).Item(0).value.ToString("N2")
                labeleff.Text = EFF
            End Using
            conn1.Close()
        End Using

    Catch ex As Exception
        MsgBox(ex.ToString)
    End Try

您正在尝试使用

访问数据表单元格中的值
dt.Rows(0).Item(0).value.ToString("N2")

dt.Rows(0).Item(0)(或简单地 dt.Rows(0)(0))已经 return 作为 object 的值。您使用 value 属性 从 DataGridViewCell 检索值。

"right" 方法是:

CDbl(dt.Rows(0)(0)).ToString("N2")