My previous article explains about the step by step dynamic creation of a SQL Server database, tables, and stored procedure using Visual Studio codename Whidbey and VB.NET. I hope that you got a good start up in dynamic creation of SQL Server database and tables. This article explains how we can display data using DataSet and DataGrid controls after the database is created.
A DataSet is a major component of ADO.NET architecture. It is a set of data grouped together, which is an in-memory cache of data retrieved from a data source. A DataSet consists of a collection DataTable objects. A DataTable represents one table of in-memory data. The name of the DataTable is conditionally case-sensitive only if you set the public property of CaseSensitive, which indicates whether string comparisons within the table are case-sensitive.
For example, if you named a DataTable as MyTable and if you defined the table as Mytable, it wont look for the table because DataTable name is case sensitive. DataSet and DataView are the two data objects that use the DataTable.
Some of the public properties of DataTable are shown below:
Properties Description
CaseSensitiveThis property returns a Boolean value which checks if the table name is case-sensitive. It returns
Trueif the comparison is case-sensitive; otherwise,False. For example, if you named aDataTableasMyTableand if you defined the table asMytable, it wont look for the table.The
CaseSensitiveproperty affects string comparisons in sorting, searching, and filtering.ChildRelationsSimply, it is the relationship between two tables. It is just like database relationship keys such as primary key, secondary key etc., which will relate two tables using a key field.
ColumnsDatabase fields or tuples.
ConstraintsConstraints maintained for relationship between tables using keys such as primary key, index etc.
DataSetRetrieves a set of data or records based on your table name.
DefaultViewCustomized view of the table such as filtered view, or a cursor position.
HasErrorsIf any row has errors, display errors.
LocaleLocal information to compare the strings.
MinimumCapacityInitial size of the table.
ParentRelationsAny relationship occuring with parent table.
PrimaryKeyA key used for unique identification of a row.
RowsNumber of rows as collections.
TableNameName of the database table.
Some of the public methods of a DataTable are shown below:
AcceptChangesCommits a transaction.
BeginInitInitialization of
DataTable.BeginLoadDataTurns off notifications, index maintenance, and constraints.
ClearClears all the records from
DataTable.CloneCopy the structure to another table (including constraints, key fields, schemas etc.).
ComputeFilter data based on expression.
CopyCopies the database structure and data (not like
Clone).DisposeRelease from memory (unload).
EndInitFires when initialization ends.
EndLoadDataFires when load data from
DataTableends.GetErrorsGets an array of
DataRowobjects that contain errors.ImportRowImporting records.
LoadDataRowUpdates the rows based on the condition. If no matching records found, it will insert the records.
NewRowCreates a new row in
DataTable.RejectChangesRolls back the changes.
ResetReset the
DataTablein original position.SelectGets an array of data records.
Some of the events associated with DataTable are ColumnChanged, ColumnChanging, RowChanged, RowChanging, RowDeleted, RowDeleting etc.
Note: System.Data namespace is used for including into your project, which consists mostly of the classes that constitute the ADO.NET architecture. The assembly name used for creating the DataSet object is System.Data in System.Data.dll file.
SQLDataAdapter class is used to retrieve and update the database records in a DataSet. It is a bridge between SQL Server and DataSet.
There are two methods used for adding or updating records. They are:
Addmethod which will fill or refresh the rows or records in aDataSet.Updatemethod used for updating the records in aDataSet. Please note that this will call the respective SQL statements such asINSERT,UPDATE, orDELETEbased on theSqlAdapterstate.
The following lines of code will help you to understand how the SqlDataAdapter is responsible for using a SqlCommand object to fill a DataSet.
\' fill a DataSet.
\' A SqlCommand object is used to execute sql statements,
\' which we already discussed the Article 1
Dim Mycmd As New SqlCommand(SELECT * FROM dbo.Customer, myConnection)
Dim mySqlDataAdapter As New SqlDataAdapter(Mycmd)
Dim mydsCustomer As New DataSet()
mySqlDataAdapter.Fill(mydsCustomer, "Customer")
About DataGrid Control
A DataGrid control fills the rows from a data source in a table. It is used to retrieve and update the database records. The DataGrid control supports selection, editing, deleting, paging, and sorting.
Different column types in a DataGrid determine the behavior of the columns in the control. Some of the column types are BoundColumn, ButtonColumn, EditCommandColumn, HyperLinkColumn, and TemplateColumn etc.
Note: System.Web.UI.WebControls namespace is used for including this object into your application. The assembly name used for creating the DataGrid control is System.Web in System.Web.dll file.
A DataGrid control allows you to select, sort and edit the items from a data source in a table.
- Bind a
DataGridto theDataSet.First, you need to bind the
DataSetinto aDataGrid, then set theVisibleproperty toTrue. If you dont set theVisibleproperty toTrue, theDataGridwill still appear, but the scroll bar will be missing.\' Set the DataGrid caption, bind it to the DataSet, and then make it \' Visible mydgCustomer.CaptionText = "Customer" \' Notice here that instead of using the DataSet table name, \' "customers", the alternate syntax of table index is used. mydgCustomer.DataSource = mySqlDataAdapter.Tables(0) mydgCustomer.Visible = True
Notice the syntax
mySqlDataAdapter.Tables(0), you can also use the alternate syntax using theDataSettable name Customer. - Custom formatting a
DataGrid.Table style object allows you to custom format the
DataGridobject. The object name for custom formatting aDataGridobject is calledDataGridTableStyle. It represents the table drawn by theSystem.Windows.Forms.DataGridcontrol at run time. It is a class file that represents applying custom formatting to draw the grid.The following is the list of
DataGridTableStyleproperties that can be set to overrideSystem.Windows.Forms.DataGridcontrol properties. This way, it allows your own custom formatting.AllowSortingproperty allows you to set the sorting based on the user clicks on each column header, which will sort either in ascending or descending order. When theAllowSortingproperty is set toTrue, a triangle appears in each column header indicating the direction of the sort. The user can click on any column header to sort the grid by that column. Clicking the column a second time changes the direction of the sort. It returnsTrueif sorting is allowed, otherwise, it returnsFalse. The default value of this property isTrue.AlternatingBackColorallows you to set the alternate row colors (or gets or sets the background color of odd-numbered rows of the grid).mydgCustomer.AlternatingBackColor = System.Drawing.Color.Red
BackColorproperty sets the background color of the object.ColumnHeadersVisibleproperty allows you to hide or make visible the column headers in aDataGridcontrol on your form.ForeColorallows you set the foreground color of yourDataGridcontrol.GridLineColorallows you set theDataGridline color.GridLineStyleallows you to set the style ofDataGrid.mydgCustomer.GridLineStyle = System.Windows.Forms.DataGridLineStyle.None mydgCustomer.GridLineStyle = System.Windows.Forms.DataGridLineStyle.SolidHeaderBackColorallows you to set or get the background color of the headers.HeaderFontallows you to set or get the header font on theDataGridcontrol.HeaderForeColorsets the foreground color of the column headers.LinkColorallows you to set the color of a web link text.PreferredColumnWidthallows you to set theDataGridcolumn width.PreferredRowHeightallows you to set theDataGridrow height.ReadOnlyproperty allows you to set theDataGridto read only. No editing is possible (update, insert or delete).RowHeadersVisibleproperty allows you to get or set the visible properties of row headers on theDataGridcontrol.
You understand now the basic functionality of DataTable and DataSet objects, DataAdapter classes, and DataGrid control. Next, I am going to explain the step by step creation of the usage of these objects or classes or controls in your .NET applications.
- Creating and opening the database connection, database objects.
If you want to learn more on creating the databases and tables, look at my previous article, which describes how to create and open a database connection using WhidBey or .NET environment. Also, the previous article explains how to open a SQL database connection if we only installed the MSDE. For solving this issue, we used SQL error exception code in .NET Whidbey.
- Add the
DataGridcontrol to your form.Add a new
DataGridcontrol to your form, name it asmydgCustomer. - Bind to a
DataGridfor display.After adding the
DataGridcontrol on your form, next task is to populate data usingDataAdapter. The following routine gets the customer information from the Mydatabase table, puts it into aDataSetwhich is used to bind to aDataGridfor display.If IsNothing(mydgCustomer.DataSource) Then Dim strMySQL As String = _ "USE MyDatabase " %26amp; vbCrLf %26amp; _ "SELECT * " %26amp; _ "FROM myStoredProcedure" Try \' The SqlConnection class allows you to communicate \' with SQL Server and DataTable. Dim myConnection As New SqlConnection(myConnection) \' A SqlCommand object is used to execute the SQL commands. Dim mycmd As New SqlCommand(strMySQL, myConnection) Dim mySqlDataAdapter As New SqlDataAdapter(mycmd) Dim mydsCustomer As New DataSet() \' The SqlDataAdapter is responsible for using \' a SqlCommand object to fill a DataSet. mySqlDataAdapter.Fill(mydsCustomer, "Customer") \' Set the DataGrid caption, bind it to the DataSet, \' and then make it Visible mydgCustomer.CaptionText = "Customer" \' Notice here that instead of using the DataSet table name, \' "Customers", the alternate syntax of table index is used. mydgCustomer.DataSource = mySqlDataAdapter.Tables(0) \' Settings to the DataGrid Styles, which will call the procedure \' setMyDataGridTableStyleProperties and the parameter \' as DataGrid setMyDataGridTableStyleProperties(mydgCustomer) mydgCustomer.Visible = True Catch sqlExc As SqlException MessageBox.Show(sqlExc.ToString, "SQL Exception Error!", _ MessageBoxButtons.OK, MessageBoxIcon.Error) End Try End If
- Update the
DataGridstyle properties.The procedure
setMyDataGridTableStylePropertiesallows you to set theDataGridstyle properties, passing theDataGridas an object parameter.First, we need to create the
DataGridstyle usingDataGridTableStyleobject, and can apply the style properties such asAlternatingBackColor,BackColor,ForeColor,GridLineColor,HeaderrBackColor,HeaderFont,HeaderForeColor,LinkColor,Mapping, etc.AddRangemethod functionality allows you to set the styles in a particular range of yourDataGridcomponent.Private Sub setMyDataGridTableStyleProperties (ByRef myDG as DataGrid) \' Use a table style object to apply custom formatting \' to the DataGrid. Dim mydgTableStyle As New DataGridTableStyle() Dim mygrdColStyle1, mygrdColStyle2, mygrdColStyle3, _ mygrdColStyle4, mygrdColStyle5 As New %26amp; _ DataGridTextBoxColumn() With mydgTableStyle .AlternatingBackColor = Color.LightCoral .BackColor = Color.LawnGreen .ForeColor = Color.LightGray .GridLineColor = Color.LightGreenrodYellow .GridLineStyle = System.Windows.Forms.DataGridLineStyle. .HeaderBackColor = Color. LightGray .HeaderFont = New Font("Courier", 10.0!, FontStyle.Bold) .HeaderForeColor = Color. LawnGreen .LinkColor = Color.Teal \' Do not forget to set the MappingName property. \' Without this, the DataGridTableStyle properties \' and any associated DataGridColumnStyle objects \' will have no effect. .MappingName = "Customers" .SelectionBackColor = Color. LawnGreen .SelectionForeColor = Color. LightGray End With \' Use column style objects to apply formatting specific \' to each column of customer table. With mygrdColStyle1 .HeaderText = "ID#" .MappingName = "CustomerID" .Width = 50 End With With mygrdColStyle2 .HeaderText = "Last Name" .MappingName = "NameLast" .Width = 140 End With With mygrdColStyle3 .HeaderText = "Address" .MappingName = "Address1" .Width = 180 End With With mygrdColStyle4 .HeaderText = "State" .MappingName = "State" .Width = 30 End With With mygrdColStyle5 .HeaderText = "Phone" .MappingName = "Phone" .Width = 70 End With \' Add the column style objects to the tables style\'s \' column styles collection. If you fail to do this the column \' styles will not apply. mydgTableStyle.GridColumnStyles.AddRange _ (New DataGridColumnStyle() _ { mygrdColStyle1, mygrdColStyle2, _ mygrdColStyle3, mygrdColStyle4, mygrdColStyle5}) \' Add the table style object to the DataGrid\'s table styles \' collection. Again, failure to add the style to the collection \' will cause the style to not take effect. myDG.TableStyles.Add(mydgTableStyle) End Sub
- Microsoft Visual Studio.Whidbey Ver 8.0 or
- Microsoft Visual Studio .NET Professional or greater.
- Windows 2000 or Windows XP.
From this article, we found the description of DataSet, DataTable objects, DataAdapter classes. Also, you got a brief idea of using DataGrid using Fill method from the DataAdapter class. It also explained how to use the styles in DataGrid.
If you need any suggestions or help, contact me at benoyraj@yahoo.com.

