DataGridView DefaultCellStyle.Format help

MondeoST24

Member
Joined
Mar 9, 2006
Messages
16
Programming Experience
Beginner
Hi,

Got this column in a DataGridView - I want to display a percentage with 2 decimal places 4.56% etc

The problem here is if the user enters 10 the grid shows 1000.00%, I want the user to enter the exact percentage not the decimal equivilent.

How can I do that?

Thanks

VB.NET:
colDiscount1.DefaultCellStyle.Format = "p2" 
colDiscount1.DefaultCellStyle.NullValue = "0.00%" 
dgVehicles.Columns.Add(colDiscount1)
 
I just googled for the same problem and ended up here so I tried this solution.

The problem with this is that it will cause you to have 100 in the database for a percentage of 100%. It might be ok or not depending on the situation, but it will force you to divide the percentage by 100 everytime you need it as a ratio to multiply values.

For example, I need to have my price list reference to a parent price list through a foreign key relationship on self and a ratio between the two so the user may create a new price list, have it reference an existing price list and enter 90% to give a 10% rebate.

Now, if it should just take the value stored using this format, it will actually multiply it by 100 because "100" is the value stored in the database. I could simply divide it by 100, but it puts implementation details in my database and I must document this behavior so other applications accessing the same database will know what to do with the values there.

In my case, it was simpler to just handle the CellParsing event of the DataGridView in this manner :

VB.NET:
Private Sub gridPriceList_CellParsing(object sender, DataGridViewCellParsingEventArgs e)  Handles gridPriceList.CellParsing

    if e.ColumnIndex = colParentPriceListRatio.Index Then
        Try 
            e.Value = Decimal.Parse(e.Value.ToString().Replace("%", "")) / 100
            e.ParsingApplied = true
        Catch ex as Exception
            ' Add some error handling.
        end try
    end if
end sub

Hope it helps someone!

By the way, I translated this from C# so there may be some syntax errors, but the logic is hidden in there. ;)
 
Back
Top