Dynamic Database Creation - 2


Introduction

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 control after the database is created.

About "DataTable" and "DataSet" Object

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 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 data table as "MyTable" and if you defined the table as "Mytable", it won't look 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 properties are shown below:





Properties Description
CaseSensitive This property returns a boolean value which checks the table name is case-sensitive. It returns true if the comparison is case-sensitive; otherwise, false. For example, if you named a data table as "MyTable" and if you defined the table as "Mytable", it won't look the table. The CaseSensitive property affects string comparisons in sorting, searching, and filtering.
ChildRelations Simply 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. 
Columns Data base fields or tuples
Constraints Constraints maintains for relationship between tables using keys such as primary key, index etc.
DataSet Retrieves a set of data or records based on your table name
DefaultView Customized view of the table such as filtered view, or a cursor position
HasErrors If any row has errors, display errors
Locale Local information to compare the strings
MinimumCapacity Initial size of the table
ParentRelations Any relationship occurs with parent table
PrimaryKey A key used for unique identification of a row
Rows Number of rows as collections
TableName  Name of the database table
 
Some of the public events of a DataTable are shown below:

Events Description
AcceptChanges Commits the transaction
BeginInit Initialization of DataTable
BeginLoadData Turns off notifications, index maintenance, and constraints
Clear Clears all the records from DataTable
Clone Copy the structure to another table(Including constraints, key fields, schemas etc.)
Compute Filter data based on expression
Copy Copies the database structure and data (not like Clone)
Dispose Release from memory (unload)
EndInit Fires during initialization ends
EndLoadData Fires during load data from DataTable ends
GetErrors Gets an array of DataRow objects that contain errors.
ImportRow Importing records
LoadDataRow  Updates the rows based on the condition. If no matching records found, it will insert the records
NewRow Creates a new row in DataTable
RejectChanges Roll back the changes
Reset Reset the DataTable in original position
Select Gets an array of data records

Some of the events associated with data tables are ColumnChanged, ColumnChanging, RowChanged, RowChanging, RowDeleted, RowDeleting etc.

Note: "System.Data" namespace is used for include 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.

About "SQLDataAdapter" Class

SQLDataAdapter class is used to retrieve and update the data base records in a DataSet. It is a bridge between SQL Server and DataSet

There are two methods used for add or update records. They are

      1. Add method which will fill or refresh the rows or records in a DataSet
      2. Update method used for updating the records in a DataSet. Please note that this will calls
          the respective SQL statements such as INSERT, UPDATE, or DELETE based on the
          SqlAdapter state.

The following lines of code helps 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 data base records using DataGrid control. 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 inlcude this object into your. The assembly name used for creating the DataGrid control is System.Web in System.Web.Dll file.

Steps to use "DataGrid" Control

A DataGrid control allows you to select, sort and edit the items from a data source in a table.

  1. Bind a DataGrid to the DataSet
    First, you need to bind the DataSet into a DataGrid, then set the visible property to true.
    If you don't set the Visible to true, the DataGrid will 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 that the syntax mySqlDataAdapter.Tables(0), you can also use the alternate syntax using the DataSet table name "Customer"
  2. Custom formatting a DataGrid
    Table style object allows you to custom formatting to the DataGrid object. The object
    name for custom formatting a DataGrid object is called "DataGridTableStyle" object. It
    represents the table drawn by the System.Windows.Forms.DataGrid control at run time. It
    is a class file that represents to apply custom formatting to drawn the grid only.

    The following is the list of DataGridTableStyle properties that can be set to override
    System.Windows.Forms.DataGrid control properties. That way it allows your own custom
    formatting.

    AllowSorting property allows you to set the sorting based on the user clicks on each
    column header, which will sort either ascending or descending order. When the
    AllowSorting property is set to true, 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 returns
    true if sorting is allowed, otherwise, it returns false value. The default value of this
    property is true.

    AlternatingBackColor allows you to set the alternative rows color (or Gets or sets the
    background color of odd-numbered rows of the grid). 

    mydgCustomer.AlternatingBackColor = System.Drawing.Color.Red

    BackColor property sets the Background color of the object
    ColumnHeadersVisible property allows you to hide or visible the column headers in a     
    DataGrid control on your form.
    ForeColor allows you set the foreground color of your DataGrid control
    GridLineColor allows you set the DataGrid line color
    GridLineStyle allows you to set the style of DataGrid

    mydgCustomer.GridLineStyle = System.Windows.Forms.DataGridLineStyle.None
    mydgCustomer.GridLineStyle = System.Windows.Forms.DataGridLineStyle.Solid

    HeaderBackColor allows you to set or get the background color of the headers
    HeaderFont allows you to set or get the header font on the DataGrid control
    HeaderForeColor sets the foreground color of the column headers
    LinkColor allows you set the color of a web link text
    PreferredColumnWidth allows you to set the DataGrid column width
    PreferredRowHeight allows you set the DataGrid row height 
    ReadOnly property allows you to set the DataGrid to read only property. No editing is
    possible (update, insert or delete).
    RowHeadersVisible property allows you to get or set the visible properties of row
    headers on the DataGrid control.

Steps to create to display data using DataSet and DataGrid control:

You understand that the basic functionality of DataTable and DataSet objects, DataAdapter classes, and DataGrid control. Next is going to explain step by step creation of the usage of these objects or classes or controls into your .NET applications.

  1. Creating and opening the DataBase Connection, Database objects.
    If you want to learn more on to create the databases and tables, look on 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.
  2. Add the DataGrid Control to your form            
    Add a new DataGrid control to your form, named it as mydgCustomer.
  3. Bind to a DataGrid for display
    After adding the DataGrid control on your form, next task is to populate data using
    DataAdapter. The following routine gets the customer information from the Mydatabase
    table puts it into a DataSet which is used to bind to a DataGrid for display. 

    If IsNothing(mydgCustomer.DataSource) Then
    Dim strMySQL As String = _
    "USE MyDatabase " & vbCrLf & _
    "SELECT * " & _
    "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

  4. The procedure "" allows you to set the DataGrid Style properties and passing the DataGrid
    as a object parameter.

    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 & _
    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

Requirements

Microsoft Visual Studio.Whidbey Ver 8.0 Or
Microsoft Visual Studio.NET Professional or greater.
Windows 2000 or Windows XP.

Summary:

From this article, it found the description of DataSet, DataTable objects, DataAdapter classes. Also, you got a brief idea of using DataGrid using fill method from DataAdapter class. It also explained how to use the styles in DataGrid.

Up Next
    Ebook Download
    View all
    Learn
    View all