Home > OS >  How to you mask a specific column in datagridview?
How to you mask a specific column in datagridview?

Time:05-04

ProductPrice     Stocks     Category
12.0             0          Drinks
50.0             0          Drinks
30.0             0          Drinks
45.0             12         Food
50.0             10         Food
60.0             15         Food

this is my datagrid table. I want to change 0 to n/a.

but the problem is that the Stocks datatype is set to integer in the database. is there any function to mask a specific column like change 0 to n/a?

I found some "almost" a solution but it changed the whole column to n/a, not the 0's. also I did tried changing the column value to = n/a but an error always says cannot convert int to string.

can anyone help me?

CodePudding user response:

I just tested this in an unbound DataGridView and it worked as expected:

Private Sub DataGridView1_CellFormatting(sender As Object, e As DataGridViewCellFormattingEventArgs) Handles DataGridView1.CellFormatting
    If e.ColumnIndex = 1 Then
        If TypeOf e.Value Is String AndAlso CStr(e.Value) = "0" Then
            e.Value = "N/A"
            e.FormattingApplied = True
        End If
    End If
End Sub

Note that the fact that that code tests the column index first and only proceeds if the cell being formatted is in the specific column of interest. If you don't do that then of course cells in every column will be affected. You need to filter for the index of the column you want. If Stocks is the second column then the index would be 1, just as in my example. If it's not, you need to change it.

This code looks for a String value because everything entered into an unbound grid will be a String. If you have bound your grid to a data source that actually contains numbers then you should look for the appropriate numeric type. Given the scenario, that would presumably be Integer, so you would want something like this:

If TypeOf e.Value Is Integer AndAlso CInt(e.Value) = 0 Then
  • Related