This Tutorial is applicable to VB.Net 2005 and VB.Net 2008.
What will our project contain?
We will have a DataGridView to hold our data and 3 Textboxes for displaying the record detail.
There are 3 buttons that will do the Adding, Saving and Deleting of Records.
There are 2 Class Level Variables used for Record Management.
There is one Sub used for selecting specific Records.
To start off with, Create a Windows Forms Project named "UnBoundDataGridView"
The Form
You should now have your Project with a Form called "Form1"
Set the Height of the Form to 650
Set the Width of the Form to 500
The DataGridView
From your toolbox, find the "Data" Tab and drag a "DataGridview" onto Form1 and name it "dtgRecords".
Move the grid to the upper left hand side of the form and set the Height and Width of the DataGridView to 400.
The Controls
Now add 3 Lables and 3 Textboxes to the Right hand side of the DataGridView. These are necessary for adding and editing records in this Tutorial.
The details for the 3 Lables are as follows:
First Label: Name = lblID
Text = “ID:”
ReadOnly = True
Second Label: Name = lblClientName
Text = “Client Name:”
Third Label: Name = lblAmount
Text = “Amount:”
The details for the 3 Textboxes are as follows:
First Textbox: Name = txtID
Second Textbox: Name = txtClientName
Third Textbox: Name = lblAmount
Next add 3 Buttons underneath the Text Boxes
The Details for the Buttons are as follows:
First Button: Name = btnAdd
Text = “Add”
Second Button: Name = btnSave
Text = “Save”
Third button: Name = btnDelete
Text = “Delete”
The Class Variables
There are 2 Class Level Variables, namely “RecordID” and “SelectedRecordID”. They will manage our records.
RecordID:
RecordID will be used for our auto incrementing the values in txtID
SelectedRecordID:
SelectedRecordID is used for finding the Record ID in “dtgRecords”
This is the code for the Form so far
Public Class Form1 Private RecordID As Integer = 0 Private SelectedRecordID As Integer End Class
Now double click anywhere on the form (not the grid or any of the controls) and you should see the code window with the Form's Load Event.
We will define 3 Columns for "dtgRecords' in the Form1_Load Event, namely an IDColumn, ClientNameColumn and an AmountColumn. Our Columns will each have their own DataType (ValueType) for sorting purposes.
The IDColumn will be our reference to the records and will auto increment as we add records and will be our reference further on.
We will also make "dtgRecords" read only since we do not want the user to edit in the DataGridView directly.
The user will not be able to add new records on the grid or delete any records either.
Furthermore the user will only be able to select one record at a time.
This is the code for the Form1_Load event.
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 'Creating the columns Dim IDColumn As New DataGridViewColumn Dim ClientNameColumn As New DataGridViewColumn Dim AmountColumn As New DataGridViewColumn 'Setting the Properties for the IDColumn IDColumn.Name = "ID" IDColumn.ValueType = GetType(Integer) IDColumn.HeaderText = "ID" IDColumn.CellTemplate = New DataGridViewTextBoxCell 'Setting the Properties for the ClientNameColumn ClientNameColumn.Name = "ClientName" ClientNameColumn.ValueType = GetType(String) ClientNameColumn.HeaderText = "Name" ClientNameColumn.CellTemplate = New DataGridViewTextBoxCell 'Setting the Properties for the AmountColumn AmountColumn.Name = "Amount" AmountColumn.ValueType = GetType(Decimal) AmountColumn.HeaderText = "Amount" AmountColumn.CellTemplate = New DataGridViewTextBoxCell With dtgRecords 'Adding the Column to the DataGridView .Columns.Add(IDColumn) .Columns.Add(ClientNameColumn) .Columns.Add(AmountColumn) 'Making the DataGridView ReadOnly since we don't want the user to edit the grid at the moment .ReadOnly = True 'allowing only one row to be selected at a time .MultiSelect = False 'restricting user capabilities on the DataGridView .AllowUserToAddRows = False .AllowUserToDeleteRows = False End With End Sub
Adding Records
Right, now we will start to write the code for Adding a Record. Go to the Form Design Windows and Double Click the Button “btnAdd”.
Before adding any record, we increment the RecordID by 1, set the value of txtID.Text = 1 and clear the other textboxes. We will disable “btnAdd” and Enable “btnSave”.
This is the code for “btnAdd”
Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click 'incrementing the RecordID RecordID += 1 txtID.Text = RecordID txtClientName.Text = "" txtAmount.Text = "" 'enabling the save button btnSave.Enabled = True 'disabling the add button btnAdd.Enabled = False End Sub
Continue Reading the next part to see how the records get saved.
Editing and Saving Records
To edit a record, the user will have to click on “dtgRecords” so we will add code to the dtgRecords’ Cell Click Event (note not the cell content click event). We call a sub called “GetExistingDataFromGrid”. So here is the code fot the “GetExisitingDataFromGrid” and the “dtgRecords” Cell Click Event
Private Sub GetExistingDataFromGrid()
With dtgRecords.SelectedRows(0)
'get the selecte record and set the values to the textboxes
SelectedRecordID = .Cells("ID").Value
txtID.Text = SelectedRecordID
txtClientName.Text = .Cells("ClientName").Value
txtAmount.Text = .Cells("Amount").Value
End With
End Sub
Private Sub dtgRecords_CellClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dtgRecords.CellClick
GetExistingDataFromGrid()
End Sub
So now that the user is able to select a record, and see its details, he can click the Save button and it will save the data.
Here is the code for “btnSave”
Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
‘Doing some validation before going ahead
If IsNumeric(txtID.Text) = False Then
MessageBox.Show("Please enter a Number for the ID Text Box", "Invalid Input", MessageBoxButtons.OK, MessageBoxIcon.Error)
txtID.Focus()
Exit Sub
End If
If Trim(txtClientName.Text) = "" Then
MessageBox.Show("Please enter a Number for the ID Text Box", "Invalid Input", MessageBoxButtons.OK, MessageBoxIcon.Error)
txtClientName.Focus()
Exit Sub
End If
If IsNumeric(txtAmount.Text) = False Then
MessageBox.Show("Please enter a Number for the Amount Text Box", "Invalid Input", MessageBoxButtons.OK, MessageBoxIcon.Error)
txtAmount.Focus()
Exit Sub
End If
‘if we were adding a record, we need to enable the add button
If btnAdd.Enabled = False Then
btnAdd.Enabled = True
'we are adding a record
dtgRecords.Rows.Add(txtID.Text, txtClientName.Text, txtAmount.Text)
'selecting the added row in the grid
dtgRecords.Rows(dtgRecords.Rows.Count - 1).Selected = True
SelectedRecordID = txtID.Text
Else
'we are not adding a record but editing a record
dtgRecords.SelectedRows.Item(0).Cells("ClientName").Value = txtClientName.Text
dtgRecords.SelectedRows.Item(0).Cells("Amount").Value = txtAmount.Text
End If
End Sub
As you can see, a little validation is taking place before we continue saving. Now if “btnAdd” is disabled, it means we will have to add a row. If not, we will just save the values.
Deleting Records
To delete records we will have to check a few things.
1. Is there a record to delete
2. If we delete a record, we will have to navigate to the first record
3. If the user has clicked on add, and does not want to save, he can click on delete and the record will not be added. Also the RecordID will decrement by 1 since clicking on add will increment it by 1
4. If the user deleted all the records and want to add a new record, the RecordID should display the correct value (remember its auto incremented).
So here is the code for “btnDelete”
Private Sub btnDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDelete.Click
'first of all check if there are rows to delete
If dtgRecords.Rows.Count > 0 Then
If btnAdd.Enabled = True Then
If MessageBox.Show("Are you sure you want to delete the selected Record?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then
dtgRecords.Rows.Remove(dtgRecords.CurrentRow)
'after the remove we need to make sure there a any rows
'to select
If dtgRecords.Rows.Count > 0 Then
dtgRecords.Rows(0).Selected = True
GetExistingDataFromGrid()
Else
'reset all the textboxes
txtID.Text = ""
txtClientName.Text = ""
txtAmount.Text = ""
'and enalbe the add button
btnAdd.Enabled = True
'disablte the save button
btnSave.Enabled = False
End If
'enabling the add button
btnAdd.Enabled = True
End If
Else
If MessageBox.Show("Are you sure you want to cancel adding a record?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then
'Because a record was not added, we need to
'decrement the RecordID by 1
RecordID -= 1
'Selecting the first record and loading its data
'to the textboxes.
dtgRecords.Rows(0).Selected = True
GetExistingDataFromGrid()
'enabling the add button
btnAdd.Enabled = True
End If
End If
Else
'The user clicked on add but cancelled again and there are
'no records
If btnAdd.Enabled = False Then
RecordID -= 1
'resetting the buttons
btnAdd.Enabled = True
btnSave.Enabled = False
'resetting the TextBoxes
txtID.Text = ""
txtClientName.Text = ""
txtAmount.Text = ""
End If
End If
End Sub
So now that we have all the necessary items in place we can test the application..
Here is the Full code for the Project
Public Class Form1
Private RecordID As Integer = 0
Private SelectedRecordID As Integer
Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
'incrementing the RecordID
RecordID += 1
txtID.Text = RecordID
txtClientName.Text = ""
txtAmount.Text = ""
'enabling the save button
btnSave.Enabled = True
'disabling the add button
btnAdd.Enabled = False
End Sub
Private Sub btnDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDelete.Click
'first of all check if there are rows to delete
If dtgRecords.Rows.Count > 0 Then
If btnAdd.Enabled = True Then
If MessageBox.Show("Are you sure you want to delete the selected Record?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then
dtgRecords.Rows.Remove(dtgRecords.CurrentRow)
'after the remove we need to make sure there a any rows
'to select
If dtgRecords.Rows.Count > 0 Then
dtgRecords.Rows(0).Selected = True
GetExistingDataFromGrid()
Else
'reset all the textboxes
txtID.Text = ""
txtClientName.Text = ""
txtAmount.Text = ""
'and enalbe the add button
btnAdd.Enabled = True
'disablte the save button
btnSave.Enabled = False
End If
'enabling the add button
btnAdd.Enabled = True
End If
Else
If MessageBox.Show("Are you sure you want to cancel adding a record?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then
'Because a record was not added, we need to
'decrement the RecordID by 1
RecordID -= 1
'Selecting the first record and loading its data
'to the textboxes.
dtgRecords.Rows(0).Selected = True
GetExistingDataFromGrid()
'enabling the add button
btnAdd.Enabled = True
End If
End If
Else
'The user clicked on add but cancelled again and there are
'no records
If btnAdd.Enabled = False Then
RecordID -= 1
'resetting the buttons
btnAdd.Enabled = True
btnSave.Enabled = False
'resetting the TextBoxes
txtID.Text = ""
txtClientName.Text = ""
txtAmount.Text = ""
End If
End If
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Creating the columns
Dim IDColumn As New DataGridViewColumn
Dim ClientNameColumn As New DataGridViewColumn
Dim AmountColumn As New DataGridViewColumn
'Setting the Properties for the IDColumn
IDColumn.Name = "ID"
IDColumn.ValueType = GetType(Integer)
IDColumn.HeaderText = "ID"
IDColumn.CellTemplate = New DataGridViewTextBoxCell
'Setting the Properties for the ClientNameColumn
ClientNameColumn.Name = "ClientName"
ClientNameColumn.ValueType = GetType(String)
ClientNameColumn.HeaderText = "Name"
ClientNameColumn.CellTemplate = New DataGridViewTextBoxCell
'This column will be sortable
ClientNameColumn.SortMode = DataGridViewColumnSortMode.Automatic
'Setting the Properties for the AmountColumn
AmountColumn.Name = "Amount"
AmountColumn.ValueType = GetType(Decimal)
AmountColumn.HeaderText = "Amount"
AmountColumn.CellTemplate = New DataGridViewTextBoxCell
'This column will be sortable
AmountColumn.SortMode = DataGridViewColumnSortMode.Automatic
With dtgRecords
.Columns.Add(IDColumn)
.Columns.Add(ClientNameColumn)
.Columns.Add(AmountColumn)
.ReadOnly = True
'allowing only one row to be selected at a time
.MultiSelect = False
.SelectionMode = DataGridViewSelectionMode.FullRowSelect
'restricting user capabilities on the DataGridView
.AllowUserToAddRows = False
.AllowUserToDeleteRows = False
End With
'Disabling the Save Button as we do not have a Record to save
'the first time
btnSave.Enabled = False
End Sub
Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
If IsNumeric(txtID.Text) = False Then
MessageBox.Show("Please enter a Number for the ID Text Box", "Invalid Input", MessageBoxButtons.OK, MessageBoxIcon.Error)
txtID.Focus()
Exit Sub
End If
If Trim(txtClientName.Text) = "" Then
MessageBox.Show("Please enter a Number for the ID Text Box", "Invalid Input", MessageBoxButtons.OK, MessageBoxIcon.Error)
txtClientName.Focus()
Exit Sub
End If
If IsNumeric(txtAmount.Text) = False Then
MessageBox.Show("Please enter a Number for the Amount Text Box", "Invalid Input", MessageBoxButtons.OK, MessageBoxIcon.Error)
txtAmount.Focus()
Exit Sub
End If
If btnAdd.Enabled = False Then
btnAdd.Enabled = True
'we are adding a record
dtgRecords.Rows.Add(txtID.Text, txtClientName.Text, txtAmount.Text)
'selecting the added row in the grid
dtgRecords.Rows(dtgRecords.Rows.Count - 1).Selected = True
SelectedRecordID = txtID.Text
Else
'we are not adding a record but editing a record
dtgRecords.SelectedRows.Item(0).Cells("ClientName").Value = txtClientName.Text
dtgRecords.SelectedRows.Item(0).Cells("Amount").Value = txtAmount.Text
End If
End Sub
Private Sub GetExistingDataFromGrid()
With dtgRecords.SelectedRows(0)
'get the selecte record and set the values to the textboxes
SelectedRecordID = .Cells("ID").Value
txtID.Text = SelectedRecordID
txtClientName.Text = .Cells("ClientName").Value
txtAmount.Text = .Cells("Amount").Value
End With
End Sub
Private Sub dtgRecords_CellClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dtgRecords.CellClick
GetExistingDataFromGrid()
End Sub
End Class
This is the end of the tutorial.






MultiQuote




|