Creating DataGrid Programmatically


Generally ASP.NET DataGrid is placed on the web form at design time. You add the <asp:DataGrid> control to the web form and then add bound columns to it. However, some times it becomes necessary to create DataGrid via code and then add it to the web form. This articles will show you how to do just that.


In order to create DataGrid programmatically you need to follow following steps

  • Create a new VS.NET project or if you prefer to code in a text editor create a .aspx file
  • Create a variable of type DataGrid
  • Set properties of overall datagrid
  • Create bound columns as needed
  • Set properties of bound columns
  • Add bound columns to DataGrid
  • Attach event handlers if any
  • Bind the grid with your data

Sample Code

Following sub routine creates a DataGrid following above steps.

Public Sub CreateGrid()
  'declare a new datagrid and set properties
   Dim DataGrid1 As New DataGrid()
   DataGrid1.BorderWidth = Unit.Pixel(2)
   DataGrid1.CellPadding = 10
   DataGrid1.GridLines = GridLines.Both
   DataGrid1.BorderColor = Color.Blue
   DataGrid1.ShowHeader = True
   DataGrid1.AutoGenerateColumns = False
   DataGrid1.SelectedItemStyle.BackColor = Color.Yellow

   'add bound columns to the datagrid
   Dim datagridcol As New BoundColumn()
   datagridcol.HeaderText = "Last Name"
   datagridcol.DataField = "lastname"

   datagridcol = New BoundColumn()
   datagridcol.HeaderText = "First Name"
   datagridcol.DataField = "firstname"

   datagridcol = New BoundColumn()
   datagridcol.HeaderText = "DOB"
   datagridcol.DataField = "BirthDate"
   datagridcol.DataFormatString = "{0:d}"

   Dim selectcol As New ButtonColumn()
   selectcol.ButtonType = ButtonColumnType.LinkButton
   selectcol.Text = "Select"
   selectcol.CommandName = "Select"

   'add event handlers
   AddHandler DataGrid1.SelectedIndexChanged,
   AddressOf DataGrid1_SelectedIndexChanged

   'bind datagrid
   DataGrid1.DataSource = GetDataSet()

   'add datagrid to the page

End Sub

The SelectionChanged event handler looks like this

   Public Sub DataGrid1_SelectedIndexChanged
	(ByVal sender As Object, ByVal args As EventArgs)
        'write your code here
   End Sub

The BindGrid method actually binds with a DataSet

    Public Function GetDataSet() As DataSet
        Dim connstr As String =
		"Integrated Security=SSPI;User ID=sa;
		Initial Catalog=Northwind;
		Data Source=WIN2000\NetSDK"
        Dim cnn As New SqlConnection(connstr)
        Dim da As New SqlDataAdapter
	("select lastname,firstname,
	birthdate from employees", cnn)
        Dim ds As New DataSet()
        da.Fill(ds, "employees")
        Return ds
    End Function

Finally we will call the CreateGrid() method in Page_Load event

   Private Sub Page_Load
	(ByVal sender As System.Object,
	 ByVal e As System.EventArgs)
	Handles MyBase.Load
   End Sub

Keep coding !

Bipin Joshi is an independent software consultant, trainer, author, and meditation teacher. He has been programming, meditating, and teaching for 25+ years. He conducts instructor-led online training courses in ASP.NET family of technologies for individuals and small groups. He is a published author and has authored or co-authored books for Apress and Wrox press. Having embraced the Yoga way of life he also teaches Ajapa Yoga to interested individuals. To know more about him click here.

Get connected : Facebook  Twitter  LinkedIn  YouTube

Posted On : 02 March 2002

Tags : ASP.NET Server Controls Data Controls