简体   繁体   中英

datagridview cell validation for integers in vb.net

How do i make validation to pass through only positive integers? I have a column which can triggers an error if it is a non-integer however users can still key in negative integer into the cells of that column .

How about using javascript code? add this js event

onkeypress=""return allowOnlyNumber(event);

then all you need is

function allowOnlyNumber(evt)
{
  var charCode = (evt.which) ? evt.which : event.keyCode
  if (charCode > 31 && (charCode < 48 || charCode > 57))
    return false;
  return true;
}

Or else you can use FilteredTextBoxExtender from AjaxControlToolkit as

<asp:TextBox ID="txtbox1" runat="server"></asp:TextBox>
            <cc1:FilteredTextBoxExtender id="ftbe" runat="server" targetcontrolid="txtbox1"
                  filtertype="Numbers" validchars="0123456987" />

Nvm i found it i willl update the link later The column index = indicates if your current cell is in that column validate it using the following code sorry for the trouble guys. The link is here Here

           If grdDataGrid.CurrentCell.ColumnIndex = 4 Then
           If Not Integer.TryParse(e.FormattedValue.ToString(), newInteger) _
            OrElse newInteger < 0 Then

            e.Cancel = True
            Me.grdDataGrid.Rows(e.RowIndex).ErrorText = "the value must be a non-negative         integer"
            MsgBox("You must enter a positive number")
        End If
     End If

Try it in your Datagridview EditingControlShowing Event ...

Private Sub DataGridView1_EditingControlShowing(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles DataGridView1.EditingControlShowing
    Try

        If UCase(sCellName) = "QUANTITY"

             AddHandler e.Control.KeyPress, AddressOf TextNumberKeypress

        End If

    Catch ex As Exception
        '... 
    End Try
End Sub


Sub TextNumberKeypress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs)
    Dim k As Byte = Asc(e.KeyChar)

    If Not IsNumSimple(k) Then
        e.Handled = True
        If Not (k = 8 Or k = 13 Or k = 1 Or k = 3 Or k = 22) Then e.Handled = True
    End If
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM