简体   繁体   中英

.net datagridview value from database change cell value when loading

I have a datagridview and it load data from database. The SPENDING_SUM is double in database, but I want change it to money in the datagridview (for example, if the database value is 1234567.00, what I want to display in the datagridview is $1,234,567.00). Don't know how to convert the value.

The related code is:

       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

To display the filed values with preceding dollar($) symbol you need not convert the field to money instead you can use something like

 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 &

if you want to convert to money,you can use a cast operator like

 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 &

anyways i prefer the first solution as it will provide better query performances.

Suppose you have a control named lblDisplay where you want to display this here is the simple code.

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

For simple use try this example.

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

Hope this answered your question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM