Search
Winners

Win Prizes

Social Presence
Twitter Twitter LinkedIn YouTube Google

Like us on Facebook
Advertisements
Top Codes Author
Mon, 28-Jul-2014 Authors
All Time Authors
Satyapriyanayak
12160
Jayakumars
8120
Niladri.biswas
6000

Latest members | More ...


(Statistics delayed by 5 minutes)

Validation of DataGridView Cell in Windows Application.

Santosh4u
Posted by Santosh4u under Windows Forms on 10/25/2009 11:07:59 PM | Views : 5185 | Status : [Member]

Description:
In Web Application Validation is little bit easy,but in Windows Application it is little bit Difficult to validate the Controls,here i am giving the Very Nice Code to Validate the DataGridView Cells.

i am Implemented Same code in My Project for Validating Cells.
Let you want to allow only digits in DataGridView Cell then Below code will very helpful.

VB.NET
'dgv (DataGridView Name)

Private Sub dgv_EditingControlShowing(ByVal sender As System.Object, ByVal e As 

System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles dgv.EditingControlShowing
AddHandler e.Control.KeyPress, AddressOf CellValidation
End Sub
Sub CellValidation(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs)
Dim strval As String = dgv.CurrentCell.EditedFormattedValue.ToString
If strval.Length <= 6 Then
Select Case Asc(e.KeyChar)
Case AscW(ControlChars.Cr) 'Enter key
e.Handled = True
Case AscW(ControlChars.Back) 'Backspace
Case 48 To 57 'Negative sign, Decimal and Numbers
Case Else ' Everything else
e.Handled = True
End Select
End If
If strval.Length >= 6 Then
Select Case Asc(e.KeyChar)
Case AscW(ControlChars.Back) 'Backspace
Case 48 To 57 'Negative sign, Decimal and Numbers
If strval.Length >= 3 Then
strval = ""
e.Handled = True
End If
Case Else ' Everything else
e.Handled = True
End Select
Exit Sub
End If
End Sub

C#.NET
 private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)

{
e.Control.KeyPress += CellValidation;
}
public void CellValidation(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
string strval = dgv.CurrentCell.EditedFormattedValue.ToString();
if (strval.Length <= 6)
{
if (System.Convert.ToInt32(e.KeyChar) == System.Convert.ToInt32('\r')) //Enter key
{
e.Handled = true;
}
else if (System.Convert.ToInt32(e.KeyChar) == System.Convert.ToInt32('\b')) //Backspace
{
}
else if (System.Convert.ToInt32(e.KeyChar) >= 48 && System.Convert.ToInt32(e.KeyChar) <= 57)
//Negative sign, Decimal and Numbers
{
}
else
{
e.Handled = true;
}
}
if (strval.Length >= 6)
{
if (System.Convert.ToInt32(e.KeyChar) == System.Convert.ToInt32('\b')) //Backspace
{
}
else if (System.Convert.ToInt32(e.KeyChar) >= 48 && System.Convert.ToInt32(e.KeyChar) <= 57)
//Negative sign, Decimal and Numbers
{
if (strval.Length >= 3)
{
strval = "";
e.Handled = true;
}
}
else
{
e.Handled = true;
}
return;
}
}


Regards
Santosh


Found interesting? Add this to:



Comments or Responses


Login to post response