473,325 Members | 2,608 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,325 software developers and data experts.

DataGrid add dynamically a column with sort header

Hi,

I'm tring to add a column to a datagrid with a linkbutton as header that can
be used to sort the column. The column and the linkbutton are added
programmatically (see below). However the problem is that when you click the
added column header it doesn't trigger the sort.

The code :

<%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false"
Inherits="Admin_Interface03.WebForm1" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>WebForm1</title>
<meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
<meta name="CODE_LANGUAGE" Content="C#">
<meta name="vs_defaultClientScript" content="JavaScript">
<meta name="vs_targetSchema"
content="http://schemas.microsoft.com/intellisense/ie5">
</HEAD>
<body MS_POSITIONING="GridLayout">
<form id="Form1" method="post" runat="server">
<ASP:DATAGRID
id="MyDataGrid"
runat="server"
HeaderStyle-ForeColor="black"
HeaderStyle-BackColor="#cccccc"
Font-Size="8pt"
Font-Name="Verdana"
CellPadding="3">
<Columns>
<asp:BoundColumn HeaderText="Sortable" DataField="EmployeeID"
SortExpression="EmployeeID" />
<asp:BoundColumn HeaderText="Not Sortable" DataField="BirthDate" />
<asp:TemplateColumn>
<HeaderTemplate>
<asp:LinkButton id="SortButton1" runat="server" CommandName="sort"
CommandArgument="LastName">LinkButton</asp:LinkButton>
</HeaderTemplate>
<ItemTemplate>
<asp:Label runat="server" Text='<%# DataBinder.Eval(Container,
"DataItem.LastName") %>' ID="Label1"/>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</ASP:DATAGRID>
</form>
</body>
</HTML>

code behind:

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace Admin_Interface03
{
public class WebForm1 : System.Web.UI.Page
{
private string sDataTableName = "Employees";
private string SortField = "";
protected System.Web.UI.WebControls.DataGrid MyDataGrid;

private void Page_Load(object sender, System.EventArgs e)
{

MyDataGrid.AutoGenerateColumns = false;
MyDataGrid.EnableViewState = true;

MyDataGrid.AllowSorting = true;
MyDataGrid.SortCommand += new
System.Web.UI.WebControls.DataGridSortCommandEvent Handler(MyDataGrid_Sort);

MyDataGrid.ShowHeader = true;
MyDataGrid.ShowFooter = true;
MyDataGrid.HorizontalAlign = HorizontalAlign.Center;
MyDataGrid.AlternatingItemStyle.BackColor =
System.Drawing.Color.FromName("#F1F1F1");
MyDataGrid.CellPadding = 3;
MyDataGrid.BackColor = System.Drawing.Color.FromName("#FFFFFF");
MyDataGrid.Width = Unit.Pixel(400);
MyDataGrid.GridLines = GridLines.Both;
MyDataGrid.BorderWidth = Unit.Pixel(4);
MyDataGrid.BorderStyle = BorderStyle.Solid;
MyDataGrid.BorderColor = System.Drawing.Color.FromName("#C4C2C2");
MyDataGrid.HeaderStyle.Font.Size = FontUnit.Point(8);
MyDataGrid.HeaderStyle.BackColor =
System.Drawing.Color.FromName("#F3F1F1");
MyDataGrid.ItemStyle.BackColor =
System.Drawing.Color.FromName("#FFFFFF");

if (!IsPostBack)
{
Bind_Grid();
}
}
public void MyDataGrid_Sort(Object sender, DataGridSortCommandEventArgs e)
{
SortField = (string)e.SortExpression;//OR SortField =
e.SortExpression.ToString();
Response.Write("MyDataGrid_Sort-SortField="+SortField+"<br>");
Bind_Grid();
}
public void Bind_Grid()
{
Response.Write("SortField="+SortField+"<br>");

string sSqlQuery;
if(SortField.Length>0)
{sSqlQuery = "SELECT * FROM "+sDataTableName+" ORDER BY "+SortField;}
else
{sSqlQuery = "SELECT * FROM "+sDataTableName;}

Response.Write("sSqlQuery="+sSqlQuery+"<br>");

System.Data.SqlClient.SqlConnection oConnection = HERE YOU NEED TO CREATE
A CONNECTION TO NORTHWIND

System.Data.SqlClient.SqlCommand oCommand = new
System.Data.SqlClient.SqlCommand(sSqlQuery, oConnection);
System.Data.SqlClient.SqlDataReader oDataReader =
oCommand.ExecuteReader();

System.Web.UI.WebControls.TemplateColumn oTemplateColumn;
oTemplateColumn = new TemplateColumn();
//oTemplateColumn.SortExpression = oDataReader.GetName(0);
oTemplateColumn.HeaderTemplate = new
DataGridTemplate(ListItemType.Header, oDataReader.GetName(0));
oTemplateColumn.ItemTemplate = new DataGridTemplate(ListItemType.Item,
oDataReader.GetName(0));

MyDataGrid.Columns.Add(oTemplateColumn);
MyDataGrid.DataSource = oDataReader;
MyDataGrid.DataBind();

oDataReader.Close();
oConnection.Close();
}

#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}

/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.Load += new System.EventHandler(this.Page_Load);

}
#endregion
}
public class DataGridTemplate : ITemplate
{
ListItemType templateType;
string columnName;

public DataGridTemplate(ListItemType type, string colname)
{
templateType = type;
columnName = colname;
}
public void InstantiateIn(System.Web.UI.Control container)
{
Label lb;
switch(templateType)
{
case ListItemType.Header:
LinkButton oLinkButton = new LinkButton();
oLinkButton.Text = "<B>"+columnName+"</B>";
oLinkButton.ID = "SortLink";
oLinkButton.CommandName = "sort";
oLinkButton.CommandArgument = columnName;
// oLinkButton.Command+= new
System.Web.UI.WebControls.CommandEventHandler(OnSo rtCommand);
container.Controls.Add(oLinkButton); //adds the Control to the Controls
collection of the parent control
break;
case ListItemType.Item:
lb = new Label();
lb.DataBinding += new EventHandler(TemplateControl_DataBinding);
container.Controls.Add(lb);
break;
case ListItemType.Footer:
lb = new Label();
lb.Text = "<I>" + columnName + "</I>";
container.Controls.Add(lb);
break;
}
}
private void TemplateControl_DataBinding(object sender,System.EventArgs e)
{
DataGridItem container;
Label oLabel;
oLabel = (Label) sender;
container = (DataGridItem) oLabel.NamingContainer;
oLabel.Text += DataBinder.Eval(container.DataItem, columnName);
}
}
}
Any help on this would be great.

Thanks in advance.

Nov 16 '05 #1
1 8884
I think is because in the OnLoad event is to late to register methods to
controls events
Why don't you use the property menu to set the MyDataGrid_Sort method to the
SortCommand event?
So it will be placed in the InitializeComponent method.
You can alwys add it in the OnInit() method after the call to the
base.OnInit()
or in the html page inside the datagrid tag as parameter <...
OnSortCommand="MyDataGrid_Sort" ...>

"Webgour" <ol****@gsmzoo.com> schrieb im Newsbeitrag
news:eq*************@TK2MSFTNGP12.phx.gbl...
Hi,

I'm tring to add a column to a datagrid with a linkbutton as header that can be used to sort the column. The column and the linkbutton are added
programmatically (see below). However the problem is that when you click the added column header it doesn't trigger the sort.

The code :

<%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="Admin_Interface03.WebForm1" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>WebForm1</title>
<meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
<meta name="CODE_LANGUAGE" Content="C#">
<meta name="vs_defaultClientScript" content="JavaScript">
<meta name="vs_targetSchema"
content="http://schemas.microsoft.com/intellisense/ie5">
</HEAD>
<body MS_POSITIONING="GridLayout">
<form id="Form1" method="post" runat="server">
<ASP:DATAGRID
id="MyDataGrid"
runat="server"
HeaderStyle-ForeColor="black"
HeaderStyle-BackColor="#cccccc"
Font-Size="8pt"
Font-Name="Verdana"
CellPadding="3">
<Columns>
<asp:BoundColumn HeaderText="Sortable" DataField="EmployeeID"
SortExpression="EmployeeID" />
<asp:BoundColumn HeaderText="Not Sortable" DataField="BirthDate" />
<asp:TemplateColumn>
<HeaderTemplate>
<asp:LinkButton id="SortButton1" runat="server" CommandName="sort" CommandArgument="LastName">LinkButton</asp:LinkButton>
</HeaderTemplate>
<ItemTemplate>
<asp:Label runat="server" Text='<%# DataBinder.Eval(Container,
"DataItem.LastName") %>' ID="Label1"/>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</ASP:DATAGRID>
</form>
</body>
</HTML>

code behind:

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace Admin_Interface03
{
public class WebForm1 : System.Web.UI.Page
{
private string sDataTableName = "Employees";
private string SortField = "";
protected System.Web.UI.WebControls.DataGrid MyDataGrid;

private void Page_Load(object sender, System.EventArgs e)
{

MyDataGrid.AutoGenerateColumns = false;
MyDataGrid.EnableViewState = true;

MyDataGrid.AllowSorting = true;
MyDataGrid.SortCommand += new
System.Web.UI.WebControls.DataGridSortCommandEvent Handler(MyDataGrid_Sort);
MyDataGrid.ShowHeader = true;
MyDataGrid.ShowFooter = true;
MyDataGrid.HorizontalAlign = HorizontalAlign.Center;
MyDataGrid.AlternatingItemStyle.BackColor =
System.Drawing.Color.FromName("#F1F1F1");
MyDataGrid.CellPadding = 3;
MyDataGrid.BackColor = System.Drawing.Color.FromName("#FFFFFF"); MyDataGrid.Width = Unit.Pixel(400);
MyDataGrid.GridLines = GridLines.Both;
MyDataGrid.BorderWidth = Unit.Pixel(4);
MyDataGrid.BorderStyle = BorderStyle.Solid;
MyDataGrid.BorderColor = System.Drawing.Color.FromName("#C4C2C2");
MyDataGrid.HeaderStyle.Font.Size = FontUnit.Point(8);
MyDataGrid.HeaderStyle.BackColor =
System.Drawing.Color.FromName("#F3F1F1");
MyDataGrid.ItemStyle.BackColor =
System.Drawing.Color.FromName("#FFFFFF");

if (!IsPostBack)
{
Bind_Grid();
}
}
public void MyDataGrid_Sort(Object sender, DataGridSortCommandEventArgs e) {
SortField = (string)e.SortExpression;//OR SortField =
e.SortExpression.ToString();
Response.Write("MyDataGrid_Sort-SortField="+SortField+"<br>");
Bind_Grid();
}
public void Bind_Grid()
{
Response.Write("SortField="+SortField+"<br>");

string sSqlQuery;
if(SortField.Length>0)
{sSqlQuery = "SELECT * FROM "+sDataTableName+" ORDER BY "+SortField;}
else
{sSqlQuery = "SELECT * FROM "+sDataTableName;}

Response.Write("sSqlQuery="+sSqlQuery+"<br>");

System.Data.SqlClient.SqlConnection oConnection = HERE YOU NEED TO CREATE A CONNECTION TO NORTHWIND

System.Data.SqlClient.SqlCommand oCommand = new
System.Data.SqlClient.SqlCommand(sSqlQuery, oConnection);
System.Data.SqlClient.SqlDataReader oDataReader =
oCommand.ExecuteReader();

System.Web.UI.WebControls.TemplateColumn oTemplateColumn;
oTemplateColumn = new TemplateColumn();
//oTemplateColumn.SortExpression = oDataReader.GetName(0);
oTemplateColumn.HeaderTemplate = new
DataGridTemplate(ListItemType.Header, oDataReader.GetName(0));
oTemplateColumn.ItemTemplate = new DataGridTemplate(ListItemType.Item,
oDataReader.GetName(0));

MyDataGrid.Columns.Add(oTemplateColumn);
MyDataGrid.DataSource = oDataReader;
MyDataGrid.DataBind();

oDataReader.Close();
oConnection.Close();
}

#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}

/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.Load += new System.EventHandler(this.Page_Load);

}
#endregion
}
public class DataGridTemplate : ITemplate
{
ListItemType templateType;
string columnName;

public DataGridTemplate(ListItemType type, string colname)
{
templateType = type;
columnName = colname;
}
public void InstantiateIn(System.Web.UI.Control container)
{
Label lb;
switch(templateType)
{
case ListItemType.Header:
LinkButton oLinkButton = new LinkButton();
oLinkButton.Text = "<B>"+columnName+"</B>";
oLinkButton.ID = "SortLink";
oLinkButton.CommandName = "sort";
oLinkButton.CommandArgument = columnName;
// oLinkButton.Command+= new
System.Web.UI.WebControls.CommandEventHandler(OnSo rtCommand);
container.Controls.Add(oLinkButton); //adds the Control to the Controls collection of the parent control
break;
case ListItemType.Item:
lb = new Label();
lb.DataBinding += new EventHandler(TemplateControl_DataBinding);
container.Controls.Add(lb);
break;
case ListItemType.Footer:
lb = new Label();
lb.Text = "<I>" + columnName + "</I>";
container.Controls.Add(lb);
break;
}
}
private void TemplateControl_DataBinding(object sender,System.EventArgs e) {
DataGridItem container;
Label oLabel;
oLabel = (Label) sender;
container = (DataGridItem) oLabel.NamingContainer;
oLabel.Text += DataBinder.Eval(container.DataItem, columnName);
}
}
}
Any help on this would be great.

Thanks in advance.

Nov 16 '05 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
by: Ashish Shridharan | last post by:
Hi All I have been trying to add a control to the header cell of a datagrid on my ASP.NET page. These controls are defined in the HTML as ASP.NET web controls. They are being added into the...
3
by: Shravan Kumar | last post by:
Hi, I am using my code to set column widths of datagrid columns dynamically, but when I am setting the column widths to zero, the header text of the column whose width is made to zero is...
0
by: VMI | last post by:
My Windows datagrid has two columns: one with the data that the user will see (col_X) and the other one (a hidden one: col_sort) that'll be used to sort data. When a user clicks on col_X's column...
0
by: Sam Vanderstraeten | last post by:
Hi All, - Visual Studio 2002 - VB.NET > ASP.NET I created a DataGrid on a webform. This datagrid has sorting enabled. I want to create in the header of each column (that is a...
11
by: rkbnair | last post by:
I have created a datagrid in my aspx with the 'AllowSorting' property to true. When clicking on the column header, the page refreshes. However the sorting is not done. Am I missing anything? I...
2
by: CSL | last post by:
I am using the DataGrid in a Windows Application, how can I adjust the widths of each column individually.
3
by: TPhelps | last post by:
I have a sample of an unbound (autogeneratecolumns is true) sortable/pagable datagrid that works. I want to change one of the columns to a hyperlink. The examples I find use a bound column. I...
4
by: gane | last post by:
Hi, I am creating datagrid bound column dynamically and need to check if a datagrid column already exists?Is there a way to check this? thanks gane
2
by: gnewsgroup | last post by:
I have a GridView, in which the header of one column changes depending on the selected value of a DropDownList outside of this GridView. I did this dynamic header through protected void...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.