Wednesday, June 11, 2014

C#.NET - Check decimal value in DataGridView Cell

Where to use?




Step 1: Add DataGridViewTextBoxColumn column in DataGridView.
Step 2: Add EditingControlShowing events in DataGridView

Code:

private void dgvClientBilling_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
            System.Windows.Forms.TextBox txt = (System.Windows.Forms.TextBox)e.Control;
            txt.KeyPress += new KeyPressEventHandler(txt_KeyPress);
}


public void txt_KeyPress(object sender, KeyPressEventArgs e)
        {
            try
            {
                if ((e.KeyChar < '0' || e.KeyChar > '9') && (e.KeyChar != '\b') && (e.KeyChar != '.'))
                {
                    e.Handled = true;
                }
                else
                {
                    e.Handled = false;
                }
                if (Char.IsControl(e.KeyChar))
                {
                    e.Handled = false;
                }
                else if (Char.IsNumber(e.KeyChar) || e.KeyChar == '.')
                {
                    TextBox tb = sender as TextBox;
                    int cursorPosLeft = tb.SelectionStart;
                    int cursorPosRight = tb.SelectionStart + tb.SelectionLength;
                    string result = tb.Text.Substring(0, cursorPosLeft) + e.KeyChar + tb.Text.Substring(cursorPosRight);
                    string[] parts = result.Split('.');
                    if (parts.Length > 1)
                    {
                        if (parts[1].Length > 2 || parts.Length > 2)
                        {
                            e.Handled = true;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ExceptionHandler.HandleException(ex.ToString());
            }
        }


No comments:

Post a Comment