来自数据库的.net datagridview值在加载时更改单元格值

时间:2015-01-30 03:06:36

标签: vb.net datagridview double money-format

我有一个datagridview,它从数据库加载数据。 SPENDING_SUM在数据库中是双倍的,但我想在datagridview中将其更改为money(例如,如果数据库值为1234567.00,我想在datagridview中显示的是 $ 1,234,567.00)。不知道如何转换价值。

相关代码是:

       Using connObj As New SqlClient.SqlConnection(My.Settings.dbConnectionString)
            connObj.Open()


            querySql = "SELECT UPPER(USER_ID) AS 'USER ID', UPPER(USER_NAME) AS 'USER NAME', " & vbCrLf &
                      "CONVERT(varchar,JOIN_DATE, 103) AS 'JOIN DATE'," & vbCrLf &
                      "SPENDING_SUM AS 'SPENDING SUM' FROM USERS WHERE USER_NAME = " & vbCrLf &


            querySql = querySql + userName.Text

            Try
                adapter = New SqlDataAdapter(querySql, connObj)
                adapter.Fill(ds)
                DataGridView1.DataSource = ds.Tables(0)
            Catch ex As Exception
                logger.Error(ex.ToString)
            End Try

            connObj.Close()
        End Using

2 个答案:

答案 0 :(得分:0)

要显示带有前一美元($)符号的字段值,您无需将字段转换为金钱,而是可以使用

之类的内容
 querySql = "SELECT UPPER(USER_ID) AS 'USER ID', UPPER(USER_NAME) AS 'USER NAME', " & vbCrLf &
                      "CONVERT(varchar,JOIN_DATE, 103) AS 'JOIN DATE'," & vbCrLf & 
                      " '$' + convert(varchar(100),SPENDING_SUM) AS 'SPENDING SUM' FROM USERS WHERE USER_NAME = " & vbCrLf &

如果你想转换成金钱,你可以使用像

这样的演员
 querySql = "SELECT UPPER(USER_ID) AS 'USER ID', UPPER(USER_NAME) AS 'USER NAME', " & vbCrLf &
                      "CONVERT(varchar,JOIN_DATE, 103) AS 'JOIN DATE'," & vbCrLf &
                      "cast(SPENDING_SUM as money) AS 'SPENDING SUM' FROM USERS WHERE USER_NAME = " & vbCrLf &

无论如何我更喜欢第一种解决方案,因为它可以提供更好的查询性能。

答案 1 :(得分:0)

假设您有一个名为lblDisplay的控件,您希望在此处显示此控件的简单代码。

 lblDisplay.Text = String.Format("{0:C2}", SPENDING_SUM)

为简单起见,请尝试此示例。

 Dim Numbers As Double = 1234567.0
 lblDisplay.Text = String.Format("{0:C2}", Numbers)

希望这能回答你的问题。