datagridview cell numeric only c#
  • Hi i have price column in datagridview now i want that user can just enter number in this column not another character how can i restrict to user just numbers.
  • 2 Comments sorted by
  • Vote Up0Vote Down itworkeritworker
    38.50 Karma Accepted Answer
    Hi select Datagridview and then go to CellValidating Event and put below code its just accept number.


    decimal varDecimal;

    // we will not check the very new row is not any point in validating its initial value.
    if (DataGridView1.Rows[e.RowIndex].IsNewRow) { return true; }
    if (!decimal.TryParse(e.FormattedValue.ToString(),
    out varDecimal) || varDecimal < 0)
    {
    e.Cancel = true;
    MessageBox.Show("Kindly insert numeric value", "www.codingresolved.com", MessageBoxButtons.OK, MessageBoxIcon.Information);
    return false;
    }
    else
    {
    return true;
    }
  • try this one
    public void EditingControl_KeyPress(object sender, KeyPressEventArgs e)
    {
    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);

Howdy, Stranger!

It looks like you're new here. If you want to get involved, or you want to Ask a new Question, Please Login or Create a new Account by Clicking below

Login with Facebook

Tagged

Popular Posts of the Week

Top Posters Weekly

Optimum Creative