Reputation: 447
I have a Datagridview
that allows user to input the prices of a product. My client wants it that if I enter 2.525 in the price, it will display 2.52 and when I focus or edit the cell it should display the full vale of 2.525.
I am using this code in formatting the Datagridview
Columns but this one is rounding off the entered value and it does not display the whole value when the cell is in editing mode because i am using C2.
CustInvLines.Columns["InvLinePrice"].DefaultCellStyle.Format = C2
How will I format the cell so that it will display the whole value entered by user in edit mode and It will only display 2 decimal places after editing?
Upvotes: 1
Views: 2994
Reputation: 32443
You should format value by yourself in DataGridView.CellFormatting
event handler
private void CustInvLines_CellFormatting(object sender,
DataGridViewCellFormattingEventArgs e)
{
if (e.RowIndex < 0)
{
return;
}
var column = CustInvLines.Columns[e.ColumnIndex];
if (column.Name == "InvLinePrice")
{
var cell = CustInvLines.Rows[e.RowIndex].Cells[e.ColumnIndex];
var value = (decimal)e.Value;
if (cell.IsInEditMode)
{
e.Value = value.ToString(); // Display all digits
}
else
{
// Display only two digits of decimals without rounding
var twoDigitsValue = Math.Truncate(value * 100)/100;
e.Value = twoDigitsValue.ToString("C2");
}
}
}
Upvotes: 2
Reputation: 191
Try this on CellEndEdit
events on the DataGridView
.
private void CustInvLines_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
var column = CustInvLines.Columns[e.ColumnIndex];
if (column.Name == "InvLinePrice")
{
var val = CustInvLines.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
if (val !=null)
{
var twoDecimal = Math.Truncate(100 * decimal.Parse(val.ToString())) / 100;
CustInvLines.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = twoDecimal.ToString("C2");
}
}
}
There answers in this question will give you information about Truncate Two decimal places without rounding.
Upvotes: 0