ADO.NET 101: Data Rendering with a DataGrid Control - Formatting via Code
(Page 7 of 7 )
You may write the necessary code to format the data which becomes effective at run time. The run time formatting overrides whatever configured at design time. It is also easy to write the code for formatting the DataGrid, because you get visible cues as to the properties to be changed as shown here.

The following code added to the data retrieval shown earlier will render the DataGrid as shown in the next picture.
Private Sub Button1_Click(ByVal sender As System.Object, _ &
ByVal e As System.EventArgs) Handles Button1.Click
SqlConnection1.Open()
Dim dr As SqlClient.SqlDataReader
dr = SqlCommand1.ExecuteReader
While dr.Read
'adding formatting and style With DataGrid1
.BackColor = System.Drawing.Color.BlueViolet
.HeaderStyle.ForeColor =
System.Drawing.Color.Yellow
.CellPadding = 2
.CellSpacing = 3
.ItemStyle.ForeColor =
System.Drawing.Color.NavajoWhite
.HeaderStyle.Font.Bold = True
.PagerStyle.ForeColor = System.Drawing.Color.Red
.AlternatingItemStyle.BackColor =
System.Drawing.Color.Turquoise
.AlternatingItemStyle.ForeColor =
System.Drawing.Color.Tomato
.BorderStyle = BorderStyle.Groove
End With DataGrid1.DataSource = dr
DataGrid1.DataBind()
End While
dr.Close()
SqlConnection1.Close()
End Sub

Using the property Builder
You may also use the PropertyBuidler to build the properties of the DataGrid. In order to access the PropertyBuilder, click the link shown in the DataGrid's property window. This brings up the following window where you can configure the DataGrid's properties.

For demonstration purposes some property changes were made to the DataGrid's properties in the PropertyBuilder's window. The browser display is as shown below for these settings.

Summary
In the present tutorial the DataSource used was a DataReader which supports neither sorting nor paging. There are workarounds to add some additional code, or invoke the other interfaces that support paging, such as ArrayList, or DataTable. This will be considered in another tutorial. The DataGrid user interface is very rich and has a number of ways with which you can change the look and feel of the formatted data, all of which have been covered in the tutorial. As mentioned earlier you may mix the different methods to get the effect you want.
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |