Home > Win App > validate Datagridview column

validate Datagridview column

If you want to validate the column in the datagridview then you can choose “CellValidating”

Sample Codeing is as below

private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
DataGridViewTextBoxCell cell = dataGridView1[e.ColumnIndex, e.RowIndex] as DataGridViewTextBoxCell;

if (cell != null)
{
char[] chars = e.FormattedValue.ToString().ToCharArray();
foreach (char c in chars)
{
if (char.IsDigit(c) == false)
{
MessageBox.Show(“You have to enter digits only”);

e.Cancel = true;
break;
}
}
}
}

Suppose if you want to validate after pressing enter, then you can use as below
protected override bool ProcessDialogKey(KeyskeyData)
{
if (keyData == Keys.Enter)
{
DataGridViewCell currentCell = CurrentCell;
EndEdit();
CurrentCell = null;
CurrentCell = currentCell;
return true;
}
return base.ProcessDialogKey(keyData);
}
else you can also use EditControlShowing event

void dataGridView1_EditingControlShowing(object sender,

DataGridViewEditingControlShowingEventArgs e)

{

if (this.dataGridView1.CurrentCell.ColumnIndex == 0)

{

if (e.Control is TextBox)

{

TextBox tb = e.Control as TextBox;

tb.KeyPress -= new KeyPressEventHandler(tb_KeyPress);

tb.KeyPress += new KeyPressEventHandler(tb_KeyPress);

}

}

}

void tb_KeyPress(object sender, KeyPressEventArgs e)

{

if (!(char.IsDigit(e.KeyChar)))

{

Keys key = (Keys)e.KeyChar;

if (!(key == Keys.Back || key == Keys.Delete))

{

e.Handled = true;

}

}

}

}

Advertisements
Categories: Win App
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

%d bloggers like this: