Formatting DataGridView cell for entering percentages?
How do I format DataGridView
cell for开发者_运维知识库 entering percentages only?
This is old but in the event it will help someone else..
dataGridView1.Columns[ColumnIndexNumber].DefaultCellStyle.Format = "#.000\\%";
Even though the post does not get any younger, I think Migo's reply only answers part of the question and maybe someone might still be interested. Migo's answer explained how to display numbers as percentages, but it leaves the question of how a user can enter strings including the percentage symbol (that are interpreted as double) unanswered. Trying to convert the EditedFormattedValue of a Cell that fires the DataError event to double did the trick for me:
Private Sub dgvs_DataError(sender As Object, e As DataGridViewDataErrorEventArgs) Handles dgv.DataError
Dim dgv As DataGridView
Dim percentageClearedValue As Double
dgv = CType(sender, DataGridView)
If e.Exception IsNot Nothing Then
percentageClearedValue = ConvPercentToDbl(dgv.Rows(e.RowIndex).Cells(e.ColumnIndex).EditedFormattedValue)
If percentageClearedValue <> Double.MinValue Then
dgv.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = percentageClearedValue
dgv.UpdateCellValue(e.ColumnIndex, e.RowIndex)
dgv.EndEdit()
e.ThrowException = False
End If
End If
End Sub
The ConvPercentToDbl function tries to convert a percentage string to a double. If it does not succeed, it returns Double.MinValue.
To process and validate entered percentage values
You need to handle two events:
- CellValidating
- CellParsing
If you are deriving from the DataGridView, instead of using events, override the OnCellValidating and OnCellParsing methods.
CellValidating In this event you only reject wrong values.
private void YourGrid_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
int porcentColumnIndex = 1; // Index of your column porcentage.
if (yourGrid.IsCurrentCellDirty && e.ColumnIndex == porcentColumnIndex )
{
string inputText = e.FormattedValue.ToString().Replace("%", "");
if (!float.TryParse(inputText, out float _))
{
string headerText = yourGrid.Columns[porcentColumnIndex].HeaderText;
MessageBox.Show("The percentage format is invalid (Examples of valid values 22, 22%)", headerText, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
e.Cancel = true;
}
}
}
CellParsing In this event, you parse the input text.
private void YourGrid_CellParsing(object sender, DataGridViewCellParsingEventArgs e)
{
string inputText = e.Value.ToString().Replace("%", "");
if (float.TryParse(inputText, out float rate))
{
e.Value = rate / 100;
e.ParsingApplied = true;
}
else
{
e.ParsingApplied = false;
}
}
精彩评论