C # datatable decimal with precision

I have this code to add a new column to datatable:

DataColumn col = new DataColumn ("column", typeof (decimal));      
col.Caption = "Column";
mytable.Columns.Add (col);

How can I specify the decimal precision for this column, so the value will always be in the format I want?

+3
source share
2 answers

You can not. However, you can format the value when retrieving it from the table using the function String.Format:

String.Format("{0:0.##}", (Decimal) myTable.Rows[rowIndex].Columns[columnIndex]); 
+1
source

I had the same problem myself, and I fixed it by loading the entire schema at application startup, and then referring to the column information from the schema as needed.

Visual Basic, , , #

' in whatever class you do your database communication:
Private _database As SqlDatabase
Private Shared _schema As DataTable

Sub New()
  ' or however you handle the connection string / database creation
  Dim connectionString as String = GetConnectionString()
  _database = New SqlDatabase(connectionString)

  RetrieveSchema()
End Sub


Private Function RetrieveSchema() as DataTable
  If _schema Is Nothing Then
    Using connection As SqlConnection = _database.CreateConnection()
      connection.Open()
      _schema = connection.GetSchema("Columns")
    End Using
  End If

  return _schema
End Function


Public Function GetColumnInformation(tableName As String, columnName As String) as DataRow
  Dim firstMatchingRow as DataRow = (
    From row In _schema.Rows _
    Where (
      row("TABLE_NAME") = tableName AndAlso row("COLUMN_NAME") = columnName)
    )).FirstOrDefault()

  Return firstMatchingRow
End Function

Dim columnInformation As DataRow = Dal.GetColumnInformation(tableName, columnName)

' find the precision
Dim precision = columnInformation("NUMERIC_PRECISION")
Dim scale = columnInformation("NUMERIC_SCALE")

' convert the decimal to the column format
' e.g.: 2.345 with a scale of 2 would result in 
'       2.35
value = Decimal.Round(value, scale)
+1