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.
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
- Default.aspx (VB: Default.aspx)
- Default.aspx.cs (VB: Default.aspx.vb)
Documentation
More Examples
- Grid View for ASP.NET Web Forms - How to dynamically switch the Grid's data source and recreate columns at runtime
- Grid View for ASP.NET Web Forms - How to bind the control with autogenerated columns to different data sources at runtime
- Grid View for ASP.NET Web Forms - How to create the control and bind it to different data sources at runtime
Does this example address your development requirements/objectives?
(you will be redirected to DevExpress.com to submit your response)
Example Code
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>
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>
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");
}
}
Visual BasicImports 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