vb.netwinformsdatagridview

Assigning string value to DataGridViewTextBoxColumn gives Int32 error


Trying to assign a string "$57,834" to a DataGridViewTextBoxColumn Amt:

For Each dgr As DataGridViewRow In dgvExpSubject.Rows
    dgr.Cells("Amt").Value = Format(amt, AG.MASK_DOLLARS)

Gives this error:

DataGridView Exception: $57,834 is not a valid value for Int32

The Amt column is not Int32, it is DataGridViewTextBoxColumn. Should be able to assign a string value.


Solution

  • Your column may contain TextBoxes but the underlying data type is Integer, so the values you assign in the cells have to be Integer values. If you want those values displayed as currency then let the grid do the formatting. Set the DefaultCellStyle.Format property of the column to your format string, i.e. AG.MASK_DOLLARS, and then simply assign amt to the Value of the cell.

    BTW, if you are going to format a single value, don't use Format. We're not writing VB6 code. Call the ToString method of the value itself. That means that, if you were going to do it the way you're trying to, you do this:

    dgr.Cells("Amt").Value = amt.ToString(AG.MASK_DOLLARS)