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

.net datagridview value from database change cell value when loading

我有一个 datagridview,它从数据库加载数据。 SPENDING_SUM在数据库中是double,但我想在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

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

的内容
 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 &

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

假设你有一个名为 lblDisplay 的控件,你想在其中显示它,这里是简单的代码。

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

为了简单使用,试试这个例子。

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

希望这能回答您的问题。