答案 0 :(得分:3)
这是旧的,但如果它会帮助其他人..
dataGridView1.Columns[ColumnIndexNumber].DefaultCellStyle.Format = "#.000\\%";
答案 1 :(得分:0)
即使该帖子不再年轻,我认为Migo的回复也只能回答部分问题,也许有人可能仍然对此感兴趣。 Migo的答案说明了如何将数字显示为百分比,但是却留下了用户如何输入包括百分比符号(被解释为双精度)的字符串的问题。尝试将引发DataError事件的单元格的EditedFormattedValue转换为两倍,这对我来说是成功的秘诀:
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
ConvPercentToDbl函数尝试将百分比字符串转换为双精度。如果未成功,则返回Double.MinValue。
答案 2 :(得分:0)
处理和验证输入的百分比值
您需要处理两个事件:
如果您从 DataGridView 派生,而不是使用事件,则覆盖 OnCellValidating 和 OnCellParsing 方法。
CellValidating 在这种情况下,您只会拒绝错误的值。
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;
}
}
}
细胞解析 在此事件中,您解析输入文本。
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;
}
}