December 2017 : Online courses in ASP.NET MVC and Angular 4. Conducted by Bipin Joshi. Read more...
Registration for December 2017 batches of ASP.NET MVC / Core and Angular 4 online courses have already started. Conducted by Bipin Joshi. Book your seat today ! Click here for more details.

Creating DataGrid Programmatically

Introduction

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.

Steps

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"
   DataGrid1.Columns.Add(datagridcol)

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

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

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

   'add event handlers
   AddHandler DataGrid1.SelectedIndexChanged,
   AddressOf DataGrid1_SelectedIndexChanged

   'bind datagrid
   DataGrid1.DataSource = GetDataSet()
   DataGrid1.DataBind()

   'add datagrid to the page
   Page.Controls(1).Controls.Add(DataGrid1)

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
        CreateGrid()
   End Sub

Keep coding !


Bipin Joshi is a software consultant, an author and a yoga mentor having 22+ years of experience in software development. He also conducts online courses in ASP.NET MVC / Core and Design Patterns. 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 Meditation and Mindfulness to interested individuals. To know more about him click here.

Get connected : Twitter  Facebook  Google+  LinkedIn

Posted On : 02 March 2002


Tags : ASP.NET Server Controls Data Controls