Dynamic Datagrid Series - 1.Simple Datagrid Binding
In some of the forthcoming series in my Blog, I will start exploring Datagrid and some of the most common requirements we face in the programming life! I know it is quite late for 1.1 Datagrid since the ASP.NET 2.0 has already been released. But I never said, that I won't cover 2.0 ;o)
Let me start from the beginning and see how deep the datagrid stuff can go. One of my main intentions is to use the code-behind page model only. So, I will try to abstain from the design view as much as possible.
Requirement 1
===========
Display a table of data from your database
Let's create a new ASP.NET Web Application under Visual Basic Projects called DataGridDemo1.
Add the following lines just after your <configuration> tag in the web.config. I will be working with the "pubs" database all the time. Better to have it in the web.config.
<appSettings>
<add key="ConnectionInfo" value="server=(local);database=Pubs;user id=sa;password="/>
</appSettings>
1) Create a new Page called "BasicDataGrid.aspx"
2) Drag and drop a PlaceHolder control and change the ID to "PlaceHolder". Go to the code behind of this page and delete everything. Now paste the following...
Imports System.Data
Imports System.Data.SqlClient
'
Public Class WebForm1
Inherits System.Web.UI.Page
#Region " Web Form Designer Generated Code "
'This call is required by the Web Form Designer.
<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
End Sub
Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
'CODEGEN: This method call is required by the Web Form Designer
'Do not modify it using the code editor.
InitializeComponent()
End Sub
#End Region
Dim strConn As String = ConfigurationSettings.AppSettings("ConnectionInfo")
Dim strCommand As String = "select au_id as Author_ID, au_lname as Last_Name," & _
" au_fname as First_Name, phone as Phone_Number, state as State from authors"
Protected WithEvents PlaceHolder As System.Web.UI.WebControls.PlaceHolder
Dim dg As New DataGrid()
'
Private Sub Page_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs _
) Handles MyBase.Load
'
'Put user code to initialize the page here
Dim tblData As DataTable
tblData = GetData(strCommand, strConn)
'
dg.DataSource = tblData
dg.AllowSorting = True
dg.DataBind()
PlaceHolder.Controls.Add(dg)
End Sub
'
Private Function GetData(ByVal strCommand As String, _
ByVal strConn As String _
) As DataTable
'
Dim adpSQLAdapter As New SqlDataAdapter(strCommand, strConn)
Dim tblData As New DataTable()
'
adpSQLAdapter.Fill(tblData)
Return tblData
End Function
End Class
3) Open Solution Explorer, right click on "BasicDataGrid.aspx" and select "Set as Start Page" in the menu
4) Click on Debug -> Start and you should be able to see a very simple table of Data (with no Formatting) from the Database.
Comments
- Anonymous
September 26, 2006
Este es un data grid