This example demonstrates how to add a column to the grid when the AutoGenerateColumns property is enabled.
Overview
When the AutoGenerateColumns property is set to true
, handle the DataBound event to add a column to the Grid View control. Before you add a column, check whether this column already exists to avoid duplicate columns.
ASPx<dx:ASPxGridView ID="ASPxGridView1" runat="server" AutoGenerateColumns="True"
KeyFieldName="CategoryID" ondatabound="ASPxGridView1_DataBound">
</dx:ASPxGridView>
C#protected void ASPxGridView1_DataBound(object sender, EventArgs e) {
if (grid.Columns.IndexOf(grid.Columns["CommandColumn"]) != -1)
return;
GridViewCommandColumn col = new GridViewCommandColumn();
col.Name = "CommandColumn";
// ...
grid.Columns.Add(col);
}
Files to Review
- Default.aspx (VB: Default.aspx)
- Default.aspx.cs (VB: Default.aspx.vb)
More Examples
Example Code
ASPx<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ Register Assembly="DevExpress.Web.v13.1, Version=13.1.14.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 runat="server">
<title>How to add a column if the AutoGenerateColumns property is set to true</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<dx:ASPxGridView ID="ASPxGridView1" runat="server" AutoGenerateColumns="True" DataSourceID="ds"
KeyFieldName="CategoryID" ondatabound="ASPxGridView1_DataBound">
</dx:ASPxGridView>
<asp:AccessDataSource ID="ds" runat="server" DataFile="~/App_Data/nwind.mdb" SelectCommand="SELECT [CategoryID], [CategoryName], [Description] FROM [Categories]">
</asp:AccessDataSource>
</div>
</form>
</body>
</html>
C#using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DevExpress.Web;
public partial class _Default : System.Web.UI.Page {
protected void Page_Load (object sender, EventArgs e) {
}
protected void ASPxGridView1_DataBound (object sender, EventArgs e) {
ASPxGridView grid = sender as ASPxGridView;
if (grid.Columns.IndexOf(grid.Columns["CommandColumn"]) != -1)
return;
GridViewCommandColumn col = new GridViewCommandColumn();
col.Name = "CommandColumn";
col.ShowSelectCheckbox = true;
col.VisibleIndex = 0;
grid.Columns.Add(col);
}
}