DataGridView set a column to be a number only

Source: Internet
Author: User

Public Datagridviewtextboxeditingcontrol celledit = null;

int idx = 1;
private void Datagridview1_editingcontrolshowing (object sender, Datagridvieweditingcontrolshowingeventargs e)
{
if (this.datagridview1.currentcelladdress.x = = idx)
{
Celledit = (Datagridviewtextboxeditingcontrol) E.control;
Celledit.selectall ();
Celledit.keypress + = cells_keypress; Binding events
}
}

private void Cells_keypress (object sender, KeyPressEventArgs e)//custom Event
{
if (this.datagridview1.currentcelladdress.x = = idx)
{
if (E.keychar = = 46)
{
e.handled = false;
Return
}
if (! ( E.keychar >= ' 0 ' && e.keychar <= ' 9 ')) e.handled = true;
if (E.keychar = = ' \b ') e.handled = false;
}
}

private void Datagridview1_cellvalidating (object sender, Datagridviewcellvalidatingeventargs e)
{

if (Datagridview1.rows[e.rowindex]. IsNewRow) return;
Decimal DCI;
if (E.columnindex = = idx)
{
if (e.formattedvalue! = null && e.formattedvalue.tostring (). Length > 0)
{
if (!decimal. TryParse (E.formattedvalue.tostring (), out DCI) | | DCI < 0)
{
E.cancel = true;
MessageBox.Show ("Please enter numbers or decimals", "Prompt",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
}

DataGridView set a column to be a number only

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.