C# datagridview 验证输入时的信息
2018-01-23 本文已影响0人
a9b854aded01
private void dgvThrowDetails_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if (dgvThrowDetails.CurrentCell != null)
{
switch (dgvThrowDetails.CurrentCell.OwningColumn.Name)
{
case "SingleWeight":
case "Num":
case "Weight":
case "SinglePrice":
case "MinPrice":
case "CutLength":
case "PackingNum":
dgvTxt = (DataGridViewTextBoxEditingControl)e.Control;
dgvTxt.SelectAll();
dgvTxt.KeyPress -= new KeyPressEventHandler(Cells_KeyPress);
dgvTxt.KeyPress += new KeyPressEventHandler(Cells_KeyPress);
break;
}
}
}
private void Cells_KeyPress(object sender, KeyPressEventArgs e)
{
keyPressXS(e, dgvTxt);
}
private void keyPressXS(KeyPressEventArgs e, DataGridViewTextBoxEditingControl dgvTxt)
{
if (char.IsNumber(e.KeyChar) || e.KeyChar == '.' || e.KeyChar == (char)Keys.Back)
{
e.Handled = false; //让操作生效
int j = 0;
int k = 0;
bool flag = false;
if (dgvTxt.Text.Length == 0)
{
if (e.KeyChar == '.')
{
e.Handled = true; //让操作失效
}
}
for (int i = 0; i < dgvTxt.Text.Length; i++)
{
if (dgvTxt.Text[i] == '.')
{
j++;
flag = true;
}
if (flag)
{
if (char.IsNumber(dgvTxt.Text[i]) && e.KeyChar != (char)Keys.Back)
{
k++;
}
}
if (j >= 1)
{
if (e.KeyChar == '.')
{
e.Handled = true; //让操作失效
}
}
if (k == 7)
{
if (char.IsNumber(dgvTxt.Text[i]) && e.KeyChar != (char)Keys.Back)
{
if (dgvTxt.Text.Length - dgvTxt.SelectionStart < 3)
{
if (dgvTxt.SelectedText != dgvTxt.Text)
{
e.Handled = true; ////让操作失效
}
}
}
}
}
}
else
{
e.Handled = true;
}
}