【问题标题】:Convert SQL databound datatable cell to string with 2 decimal places, VB.net将 SQL 数据绑定数据表单元格转换为带 2 个小数位的字符串,VB.net
【发布时间】:2015-05-15 17:55:06
【问题描述】:

我目前正在使用带有 SQL Server 后端的 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

【问题讨论】:

  • sql查询完美。我已经在我的 microsoft sql server management studio management 中运行了查询。我得到的错误是“System.MissingMemberException:未找到'Double'类型的公共'值'。”
  • 函数是否需要一个 Double 并且你给它一个 Integer - WorkingHours
  • 或许,是不是datable中的数字需要先从整型转为双精度再转为字符串?
  • 我会试一试 - 如果是这样,简单的修复!

标签: sql sql-server vb.net integer decimal


【解决方案1】:

您正在尝试使用

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

但dt.Rows(0).Item(0)(或简称dt.Rows(0)(0))已经将值作为object 返回。您可以使用 value 属性从 DataGridViewCell 中检索值。

“正确”的做法是:

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

【讨论】:

    猜你喜欢
    • 2015-11-05
    • 1970-01-01
    • 2023-03-27
    • 2019-07-11
    • 1970-01-01
    • 2020-12-15
    • 2021-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多