Example E2967
Visible to All Users

Grid View for ASP.NET Web Forms - How to create columns and bind the control to different data sources at runtime

This example demonstrates how to create columns and bind the ASPxGridView to different data sources at runtime. Select items in the ASPxRadioButtonList control to switch between SQL data sources.

Bind grid to a data source at runtime

The grid does not have columns in design mode. All columns are added to the grid at runtime according to columns of the bound data source. If the data source has the insert, update, or delete command, the grid displays the command column.

Note that the grid's EnableViewState property is set to false to avoid exceptions when binding the grid to a data source.

Files to Look At

Documentation

More Examples

Does this example address your development requirements/objectives?

(you will be redirected to DevExpress.com to submit your response)

Example Code

WebSite/Default.aspx
ASPx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <%@ Register Assembly="DevExpress.Web.v15.1, Version=15.1.15.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a" Namespace="DevExpress.Web" TagPrefix="dx" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1" runat="server"> <title>How to bind ASPxGridView with manually created columns to different data sources at runtime. The grid is created in design mode.</title> </head> <body> <form id="form1" runat="server"> <table> <tr> <td valign="top"> <dx:ASPxGridView ID="grid" runat="server" ClientInstanceName="grid" OnCustomCallback="grid_CustomCallback" OnDataBinding="grid_DataBinding" EnableViewState="false" AutoGenerateColumns="False" OnRowDeleting="grid_RowDeleting" OnRowInserting="grid_RowInserting" OnRowUpdating="grid_RowUpdating"> </dx:ASPxGridView> </td> <td valign="top"> <dx:ASPxRadioButtonList ID="rblDatasources" runat="server"> <ClientSideEvents SelectedIndexChanged="function(s, e) { grid.PerformCallback(s.GetSelectedIndex()); }" /> <Items> <dx:ListEditItem Selected="True" Text="Products" /> <dx:ListEditItem Text="Categories" /> <dx:ListEditItem Text="Shippers" /> </Items> </dx:ASPxRadioButtonList> </td> </tr> </table> <asp:SqlDataSource ID="dsProducts" runat="server" ConnectionString="Data Source=(local);Initial Catalog=Northwind;Integrated Security=True" ProviderName="System.Data.SqlClient" DeleteCommand="DELETE FROM [Products] WHERE [ProductID] = @ProductID" InsertCommand="INSERT INTO [Products] ([ProductName], [QuantityPerUnit], [UnitPrice]) VALUES (@ProductName, @QuantityPerUnit, @UnitPrice)" SelectCommand="SELECT [ProductID], [ProductName], [QuantityPerUnit], [UnitPrice] FROM [Products]" UpdateCommand="UPDATE [Products] SET [ProductName] = @ProductName, [QuantityPerUnit] = @QuantityPerUnit, [UnitPrice] = @UnitPrice WHERE [ProductID] = @ProductID"> <DeleteParameters> <asp:Parameter Name="ProductID" Type="Int32" /> </DeleteParameters> <InsertParameters> <asp:Parameter Name="ProductName" Type="String" /> <asp:Parameter Name="QuantityPerUnit" Type="String" /> <asp:Parameter Name="UnitPrice" Type="Decimal" /> </InsertParameters> <UpdateParameters> <asp:Parameter Name="ProductName" Type="String" /> <asp:Parameter Name="QuantityPerUnit" Type="String" /> <asp:Parameter Name="UnitPrice" Type="Decimal" /> <asp:Parameter Name="ProductID" Type="Int32" /> </UpdateParameters> </asp:SqlDataSource> <asp:SqlDataSource ID="dsCategories" runat="server" ConnectionString="Data Source=(local);Initial Catalog=Northwind;Integrated Security=True" ProviderName="System.Data.SqlClient" DeleteCommand="DELETE FROM [Categories] WHERE [CategoryID] = @CategoryID" InsertCommand="INSERT INTO [Categories] ([CategoryName], [Description]) VALUES (@CategoryName, @Description)" SelectCommand="SELECT [CategoryID], [CategoryName], [Description] FROM [Categories]" UpdateCommand="UPDATE [Categories] SET [CategoryName] = @CategoryName, [Description] = @Description WHERE [CategoryID] = @CategoryID"> <DeleteParameters> <asp:Parameter Name="CategoryID" Type="Int32" /> </DeleteParameters> <InsertParameters> <asp:Parameter Name="CategoryName" Type="String" /> <asp:Parameter Name="Description" Type="String" /> </InsertParameters> <UpdateParameters> <asp:Parameter Name="CategoryName" Type="String" /> <asp:Parameter Name="Description" Type="String" /> <asp:Parameter Name="CategoryID" Type="Int32" /> </UpdateParameters> </asp:SqlDataSource> <asp:SqlDataSource ID="dsShippers" runat="server" ConnectionString="Data Source=(local);Initial Catalog=Northwind;Integrated Security=True" ProviderName="System.Data.SqlClient" SelectCommand="SELECT [ShipperID], [CompanyName], [Phone] FROM [Shippers]"> </asp:SqlDataSource> </form> </body> </html>
Default.aspx
ASPx
<%@ Page Language="vb" AutoEventWireup="true" CodeFile="Default.aspx.vb" Inherits="_Default" %> <%@ Register Assembly="DevExpress.Web.v15.1, Version=15.1.15.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a" Namespace="DevExpress.Web" TagPrefix="dx" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1" runat="server"> <title>How to bind ASPxGridView with manually created columns to different data sources at runtime. The grid is created in design mode.</title> </head> <body> <form id="form1" runat="server"> <table> <tr> <td valign="top"> <dx:ASPxGridView ID="grid" runat="server" ClientInstanceName="grid" OnCustomCallback="grid_CustomCallback" OnDataBinding="grid_DataBinding" EnableViewState="false" AutoGenerateColumns="False" OnRowDeleting="grid_RowDeleting" OnRowInserting="grid_RowInserting" OnRowUpdating="grid_RowUpdating"> </dx:ASPxGridView> </td> <td valign="top"> <dx:ASPxRadioButtonList ID="rblDatasources" runat="server"> <ClientSideEvents SelectedIndexChanged="function(s, e) { grid.PerformCallback(s.GetSelectedIndex()); }" /> <Items> <dx:ListEditItem Selected="True" Text="Products" /> <dx:ListEditItem Text="Categories" /> <dx:ListEditItem Text="Shippers" /> </Items> </dx:ASPxRadioButtonList> </td> </tr> </table> <asp:SqlDataSource ID="dsProducts" runat="server" ConnectionString="Data Source=(local);Initial Catalog=Northwind;Integrated Security=True" ProviderName="System.Data.SqlClient" DeleteCommand="DELETE FROM [Products] WHERE [ProductID] = @ProductID" InsertCommand="INSERT INTO [Products] ([ProductName], [QuantityPerUnit], [UnitPrice]) VALUES (@ProductName, @QuantityPerUnit, @UnitPrice)" SelectCommand="SELECT [ProductID], [ProductName], [QuantityPerUnit], [UnitPrice] FROM [Products]" UpdateCommand="UPDATE [Products] SET [ProductName] = @ProductName, [QuantityPerUnit] = @QuantityPerUnit, [UnitPrice] = @UnitPrice WHERE [ProductID] = @ProductID"> <DeleteParameters> <asp:Parameter Name="ProductID" Type="Int32" /> </DeleteParameters> <InsertParameters> <asp:Parameter Name="ProductName" Type="String" /> <asp:Parameter Name="QuantityPerUnit" Type="String" /> <asp:Parameter Name="UnitPrice" Type="Decimal" /> </InsertParameters> <UpdateParameters> <asp:Parameter Name="ProductName" Type="String" /> <asp:Parameter Name="QuantityPerUnit" Type="String" /> <asp:Parameter Name="UnitPrice" Type="Decimal" /> <asp:Parameter Name="ProductID" Type="Int32" /> </UpdateParameters> </asp:SqlDataSource> <asp:SqlDataSource ID="dsCategories" runat="server" ConnectionString="Data Source=(local);Initial Catalog=Northwind;Integrated Security=True" ProviderName="System.Data.SqlClient" DeleteCommand="DELETE FROM [Categories] WHERE [CategoryID] = @CategoryID" InsertCommand="INSERT INTO [Categories] ([CategoryName], [Description]) VALUES (@CategoryName, @Description)" SelectCommand="SELECT [CategoryID], [CategoryName], [Description] FROM [Categories]" UpdateCommand="UPDATE [Categories] SET [CategoryName] = @CategoryName, [Description] = @Description WHERE [CategoryID] = @CategoryID"> <DeleteParameters> <asp:Parameter Name="CategoryID" Type="Int32" /> </DeleteParameters> <InsertParameters> <asp:Parameter Name="CategoryName" Type="String" /> <asp:Parameter Name="Description" Type="String" /> </InsertParameters> <UpdateParameters> <asp:Parameter Name="CategoryName" Type="String" /> <asp:Parameter Name="Description" Type="String" /> <asp:Parameter Name="CategoryID" Type="Int32" /> </UpdateParameters> </asp:SqlDataSource> <asp:SqlDataSource ID="dsShippers" runat="server" ConnectionString="Data Source=(local);Initial Catalog=Northwind;Integrated Security=True" ProviderName="System.Data.SqlClient" SelectCommand="SELECT [ShipperID], [CompanyName], [Phone] FROM [Shippers]"> </asp:SqlDataSource> </form> </body> </html>
WebSite/Default.aspx.cs
C#
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using DevExpress.Web; public partial class _Default : System.Web.UI.Page { enum DataSourceType { Products, Categories, Shippers } protected void Page_Init(object sender, EventArgs e) { if (!this.IsPostBack) Session.Clear(); grid.DataBind(); } protected void grid_DataBinding(object sender, EventArgs e) { (sender as ASPxGridView).DataSource = GetDataSource(); AddColumns(); } protected void grid_CustomCallback(object sender, ASPxGridViewCustomCallbackEventArgs e) { Session["selectedDataSource"] = Int32.Parse(e.Parameters); grid.Columns.Clear(); grid.AutoGenerateColumns = false; grid.DataBind(); } private SqlDataSource GetDataSource() { object o = Session["selectedDataSource"]; DataSourceType dsType = DataSourceType.Products; if (o != null) dsType = (DataSourceType)o; switch (dsType) { case DataSourceType.Categories: return dsCategories; case DataSourceType.Shippers: return dsShippers; default: return dsProducts; } } private void AddColumns() { grid.Columns.Clear(); DataView dw = (DataView)GetDataSource().Select(DataSourceSelectArguments.Empty); foreach (DataColumn c in dw.Table.Columns) AddTextColumn(c.ColumnName); grid.KeyFieldName = dw.Table.Columns[0].ColumnName; grid.Columns[0].Visible = false; AddCommandColumn(); } private void AddTextColumn(string fieldName) { GridViewDataTextColumn c = new GridViewDataTextColumn(); c.FieldName = fieldName; grid.Columns.Add(c); } private void AddCommandColumn() { SqlDataSource ds = (SqlDataSource)grid.DataSource; bool showColumn = !(String.IsNullOrEmpty(ds.UpdateCommand) && String.IsNullOrEmpty(ds.InsertCommand) && String.IsNullOrEmpty(ds.DeleteCommand)); if (showColumn) { GridViewCommandColumn c = new GridViewCommandColumn(); grid.Columns.Add(c); c.ShowEditButton = !String.IsNullOrEmpty(ds.UpdateCommand); c.ShowNewButton = !String.IsNullOrEmpty(ds.InsertCommand); c.ShowDeleteButton = !String.IsNullOrEmpty(ds.DeleteCommand); c.ShowCancelButton = true; c.ShowUpdateButton = true; } } protected void grid_RowInserting(object sender, DevExpress.Web.Data.ASPxDataInsertingEventArgs e) { throw new NotImplementedException("Operation is not allowed in demonstration mode"); } protected void grid_RowDeleting(object sender, DevExpress.Web.Data.ASPxDataDeletingEventArgs e) { throw new NotImplementedException("Operation is not allowed in demonstration mode"); } protected void grid_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e) { throw new NotImplementedException("Operation is not allowed in demonstration mode"); } }
Default.aspx.vb
Visual Basic
Imports Microsoft.VisualBasic Imports System Imports System.Data Imports System.Configuration Imports System.Collections Imports System.Web Imports System.Web.Security Imports System.Web.UI Imports System.Web.UI.WebControls Imports System.Web.UI.WebControls.WebParts Imports System.Web.UI.HtmlControls Imports DevExpress.Web Partial Public Class _Default Inherits System.Web.UI.Page Private Enum DataSourceType Products Categories Shippers End Enum Protected Sub Page_Init(ByVal sender As Object, ByVal e As EventArgs) If (Not Me.IsPostBack) Then Session.Clear() End If grid.DataBind() End Sub Protected Sub grid_DataBinding(ByVal sender As Object, ByVal e As EventArgs) TryCast(sender, ASPxGridView).DataSource = GetDataSource() AddColumns() End Sub Protected Sub grid_CustomCallback(ByVal sender As Object, ByVal e As ASPxGridViewCustomCallbackEventArgs) Session("selectedDataSource") = Int32.Parse(e.Parameters) grid.Columns.Clear() grid.AutoGenerateColumns = False grid.DataBind() End Sub Private Function GetDataSource() As SqlDataSource Dim o As Object = Session("selectedDataSource") Dim dsType As DataSourceType = DataSourceType.Products If o IsNot Nothing Then dsType = CType(o, DataSourceType) End If Select Case dsType Case DataSourceType.Categories Return dsCategories Case DataSourceType.Shippers Return dsShippers Case Else Return dsProducts End Select End Function Private Sub AddColumns() grid.Columns.Clear() Dim dw As DataView = CType(GetDataSource().Select(DataSourceSelectArguments.Empty), DataView) For Each c As DataColumn In dw.Table.Columns AddTextColumn(c.ColumnName) Next c grid.KeyFieldName = dw.Table.Columns(0).ColumnName grid.Columns(0).Visible = False AddCommandColumn() End Sub Private Sub AddTextColumn(ByVal fieldName As String) Dim c As New GridViewDataTextColumn() c.FieldName = fieldName grid.Columns.Add(c) End Sub Private Sub AddCommandColumn() Dim ds As SqlDataSource = CType(grid.DataSource, SqlDataSource) Dim showColumn As Boolean = Not(String.IsNullOrEmpty(ds.UpdateCommand) AndAlso String.IsNullOrEmpty(ds.InsertCommand) AndAlso String.IsNullOrEmpty(ds.DeleteCommand)) If showColumn Then Dim c As New GridViewCommandColumn() grid.Columns.Add(c) c.ShowEditButton = Not String.IsNullOrEmpty(ds.UpdateCommand) c.ShowNewButton = Not String.IsNullOrEmpty(ds.InsertCommand) c.ShowDeleteButton = Not String.IsNullOrEmpty(ds.DeleteCommand) c.ShowCancelButton = True c.ShowUpdateButton = True End If End Sub Protected Sub grid_RowInserting(ByVal sender As Object, ByVal e As DevExpress.Web.Data.ASPxDataInsertingEventArgs) Throw New NotImplementedException("Operation is not allowed in demonstration mode") End Sub Protected Sub grid_RowDeleting(ByVal sender As Object, ByVal e As DevExpress.Web.Data.ASPxDataDeletingEventArgs) Throw New NotImplementedException("Operation is not allowed in demonstration mode") End Sub Protected Sub grid_RowUpdating(ByVal sender As Object, ByVal e As DevExpress.Web.Data.ASPxDataUpdatingEventArgs) Throw New NotImplementedException("Operation is not allowed in demonstration mode") End Sub End Class

Disclaimer: The information provided on DevExpress.com and affiliated web properties (including the DevExpress Support Center) is provided "as is" without warranty of any kind. Developer Express Inc disclaims all warranties, either express or implied, including the warranties of merchantability and fitness for a particular purpose. Please refer to the DevExpress.com Website Terms of Use for more information in this regard.

Confidential Information: Developer Express Inc does not wish to receive, will not act to procure, nor will it solicit, confidential or proprietary materials and information from you through the DevExpress Support Center or its web properties. Any and all materials or information divulged during chats, email communications, online discussions, Support Center tickets, or made available to Developer Express Inc in any manner will be deemed NOT to be confidential by Developer Express Inc. Please refer to the DevExpress.com Website Terms of Use for more information in this regard.