我尝试制作一个自动格式系统,例如:将数字编号为5124.25
用户输入5:0,05
用户输入1:0,51
用户输入2:5,12
用户输入4:51,24
用户输入2:512,42
用户输入5:5124,25
我需要将这个“格式样式”放在datagridview的一列中,为此,我试试这个:
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
var temp = (DataGridView)sender;
if (temp.CurrentCell.ColumnIndex == 4)
{
e.Control.PreviewKeyDown -= Control_PreviewKeyDown;
e.Control.PreviewKeyDown += new PreviewKeyDownEventHandler(Control_PreviewKeyDown);
}
}
void Control_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
var temp = (DataGridViewTextBoxEditingControl)sender;
TextBoxMoeda(ref temp, e);
/*if (e.KeyCode == Keys.Escape)
{
System.Diagnostics.Debug.Print("escape pressed");
}*/
}
public static void TextBoxMoeda(ref DataGridViewTextBoxEditingControl txt, PreviewKeyDownEventArgs e)
{
string n = string.Empty;
double v = 0;
try
{
n = txt.Text.Replace(",", "").Replace(".", "").Replace("R$", "");
if (n.Length == 0)
txt.Text = "0,00";
else if (n.Length == 1)
txt.Text = "0,0" + n;
else if (n.Length == 2)
txt.Text = "0," + n;
else if(n.Length > 2)
txt.Text = n.Substring(0, n.Length - 2) + "," +
n.Substring(n.Length - 2);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "TextBoxMoeda");
}
}
如何制作这种dinamic格式的钱?
答案 0 :(得分:0)
尝试将DefaultCellStyle.Format设置为“c”以获取金钱或任何您想要的格式,然后订阅CellFormatting事件:
dataGridView1.Columns["Column2"].DefaultCellStyle.Format = "c";
dataGridView1.CellFormatting += dataGridView1_CellFormatting;
尝试将信息解析为十进制格式:
void dataGridView1_CellFormatting(object sender,
DataGridViewCellFormattingEventArgs e) {
if (e.CellStyle.Format == "c" &&
e.RowIndex != this.dataGridView1.NewRowIndex) {
decimal d;
if (e.Value != null && decimal.TryParse(e.Value.ToString(), out d)) {
e.Value = d.ToString("c");
}
}
}