Menu Horisontal

Sabtu, 12 Mei 2012

Membatasi Input Pada DataGridView

Buatlah sebuah Proyek di VB 2005. tambahkan komponen Datagridview dan sebuah Button lalu tambahkan kode seperti dibawah ini :


Imports System.Data.SqlClient
Public Class Form1
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        DataGridView1.ColumnCount = 3
        DataGridView1.Columns(0).Name = "Product ID"
        DataGridView1.Columns(1).Name = "Product Name"
        DataGridView1.Columns(2).Name = "Product_Price"

        Dim row As String() = New String() {"1", "Product 1", "1000"}
        DataGridView1.Rows.Add(row)
        row = New String() {"2", "Product 2", "2000"}
        DataGridView1.Rows.Add(row)
        row = New String() {"3", "Product 3", "3000"}
        DataGridView1.Rows.Add(row)
        row = New String() {"4", "Product 4", "4000"}
        DataGridView1.Rows.Add(row)

        Dim cmb As New DataGridViewComboBoxColumn()
        cmb.HeaderText = "Select Data"
        cmb.Name = "cmb"
        cmb.MaxDropDownItems = 4
        cmb.Items.Add("True")
        cmb.Items.Add("False")
        DataGridView1.Columns.Add(cmb)
    End Sub

    Private Sub DataGridView1_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick

    End Sub

    Private Sub DataGridView1_CellEndEdit(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellEndEdit
        If (e.ColumnIndex = 0) Then   ' Checking numeric value for Column1 only
            If DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value <> Nothing Then
                Dim value As String = DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value.ToString()
                If Not Information.IsNumeric(value) Then
                    MessageBox.Show("Please enter numeric value.")
                    DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = String.Empty
                    Exit Sub
                End If
            End If
        End If
    End Sub
    Private Sub DataGridView1_DataError(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewDataErrorEventArgs) Handles DataGridView1.DataError
        MessageBox.Show("Please enter a numeric value")
    End Sub

End Class

Coba masukkan karakter di kolom 1 , makan aka ditolak oleh program
Thanks semoga bermanfaat

Tidak ada komentar: