Page 1 of 1

A Un-Bound DataGridView How to use a Un-Bound DataGridView for Adding, Deleting and Editing Re Rate Topic: -----

#1 motcom  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 290
  • View blog
  • Posts: 1,371
  • Joined: 16-June 08

Post icon  Posted 21 October 2009 - 03:41 AM

This Tutorial will show you how to add, delete and edit data in a DataGridView without using a DataTable or DataSet. So basically it is Unbound.

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.

Is This A Good Question/Topic? 0
  • +

Replies To: A Un-Bound DataGridView

#2 Guest_RaZZ*


Reputation:

Posted 08 March 2010 - 07:51 AM

hi,
Great tutorial you have there!
I have tried your code and there is a bit of problem.
When the first time running the program, the save button is disabled.
So I insert some data and use the Add button, but the datagrid did not seems to add the data. Or I misunderstood here?

However, is this code you given here is saved the data inside even the program is reboot?

Awaiting your response :)

Regards,
Razlan
Was This Post Helpful? 0

#3 motcom  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 290
  • View blog
  • Posts: 1,371
  • Joined: 16-June 08

Posted 30 March 2010 - 05:57 AM

You have to Click on Add First, then click on Save...

The data is not saved, its a "Un-Bound" grid, to save it somewhere, i suggest you use datasets you can use them with XML files, Access, SQL and SQL Express and MySQL (you need the connector though).

The code will change drastically if its bound to data. What I basically wanted to show was how to use the DataGridView without Databinding...
Was This Post Helpful? 0
  • +
  • -

#4 MikeNewman  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 06-April 09

Posted 05 August 2011 - 02:47 PM

View Postmotcom, on 30 March 2010 - 05:57 AM, said:

You have to Click on Add First, then click on Save...

The data is not saved, its a "Un-Bound" grid, to save it somewhere, i suggest you use datasets you can use them with XML files, Access, SQL and SQL Express and MySQL (you need the connector though).

The code will change drastically if its bound to data. What I basically wanted to show was how to use the DataGridView without Databinding...


A good tutorial if you do not need to save the input. Would it be possible to save the data using arrays rather than a database? If so, do you have an example?


Mike
Was This Post Helpful? 0
  • +
  • -

#5 bergeronjc  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 19
  • Joined: 29-October 13

Posted 03 December 2013 - 09:35 AM

I have some issues with this. Under every '<' there's an error that says "Type expected".

The IDColumn, ClientNameColumn and AmountColumn all say: is not declared. It may be inaccessible due to its protection level.

I first type it all myself then I used the copy option and pasted the code into VS. I get the error both ways. Looking through the rest of the code I do not see how the error will go away.
Was This Post Helpful? 0
  • +
  • -

#6 andrewsw  Icon User is online

  • It's just been revoked!
  • member icon

Reputation: 3624
  • View blog
  • Posts: 12,535
  • Joined: 12-December 12

Posted 03 December 2013 - 04:32 PM

Quote

Under every '<' there's an error that says "Type expected".

I don't follow, there are no angles '<' in the code(?). Please post a code-snippet of where this error occurs.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1