473,573 Members | 2,851 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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
programmaticall y (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="Web Form1.aspx.cs" AutoEventWireup ="false"
Inherits="Admin _Interface03.We bForm1" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>WebForm1 </title>
<meta name="GENERATOR " Content="Micros oft Visual Studio .NET 7.1">
<meta name="CODE_LANG UAGE" Content="C#">
<meta name="vs_defaul tClientScript" content="JavaSc ript">
<meta name="vs_target Schema"
content="http://schemas.microso ft.com/intellisense/ie5">
</HEAD>
<body MS_POSITIONING= "GridLayout ">
<form id="Form1" method="post" runat="server">
<ASP:DATAGRID
id="MyDataGrid "
runat="server"
HeaderStyle-ForeColor="blac k"
HeaderStyle-BackColor="#ccc ccc"
Font-Size="8pt"
Font-Name="Verdana"
CellPadding="3" >
<Columns>
<asp:BoundColum n HeaderText="Sor table" DataField="Empl oyeeID"
SortExpression= "EmployeeID " />
<asp:BoundColum n HeaderText="Not Sortable" DataField="Birt hDate" />
<asp:TemplateCo lumn>
<HeaderTemplate >
<asp:LinkButt on id="SortButton1 " runat="server" CommandName="so rt"
CommandArgument ="LastName">Lin kButton</asp:LinkButton>
</HeaderTemplate>
<ItemTemplate >
<asp:Label runat="server" Text='<%# DataBinder.Eval (Container,
"DataItem.LastN ame") %>' ID="Label1"/>
</ItemTemplate>
</asp:TemplateCol umn>
</Columns>
</ASP:DATAGRID>
</form>
</body>
</HTML>

code behind:

using System;
using System.Collecti ons;
using System.Componen tModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.Sess ionState;
using System.Web.UI;
using System.Web.UI.W ebControls;
using System.Web.UI.H tmlControls;
namespace Admin_Interface 03
{
public class WebForm1 : System.Web.UI.P age
{
private string sDataTableName = "Employees" ;
private string SortField = "";
protected System.Web.UI.W ebControls.Data Grid MyDataGrid;

private void Page_Load(objec t sender, System.EventArg s e)
{

MyDataGrid.Auto GenerateColumns = false;
MyDataGrid.Enab leViewState = true;

MyDataGrid.Allo wSorting = true;
MyDataGrid.Sort Command += new
System.Web.UI.W ebControls.Data GridSortCommand EventHandler(My DataGrid_Sort);

MyDataGrid.Show Header = true;
MyDataGrid.Show Footer = true;
MyDataGrid.Hori zontalAlign = HorizontalAlign .Center;
MyDataGrid.Alte rnatingItemStyl e.BackColor =
System.Drawing. Color.FromName( "#F1F1F1");
MyDataGrid.Cell Padding = 3;
MyDataGrid.Back Color = System.Drawing. Color.FromName( "#FFFFFF");
MyDataGrid.Widt h = Unit.Pixel(400) ;
MyDataGrid.Grid Lines = GridLines.Both;
MyDataGrid.Bord erWidth = Unit.Pixel(4);
MyDataGrid.Bord erStyle = BorderStyle.Sol id;
MyDataGrid.Bord erColor = System.Drawing. Color.FromName( "#C4C2C2");
MyDataGrid.Head erStyle.Font.Si ze = FontUnit.Point( 8);
MyDataGrid.Head erStyle.BackCol or =
System.Drawing. Color.FromName( "#F3F1F1");
MyDataGrid.Item Style.BackColor =
System.Drawing. Color.FromName( "#FFFFFF");

if (!IsPostBack)
{
Bind_Grid();
}
}
public void MyDataGrid_Sort (Object sender, DataGridSortCom mandEventArgs e)
{
SortField = (string)e.SortE xpression;//OR SortField =
e.SortExpressio n.ToString();
Response.Write( "MyDataGrid_Sor t-SortField="+Sor tField+"<br>");
Bind_Grid();
}
public void Bind_Grid()
{
Response.Write( "SortField="+So rtField+"<br>") ;

string sSqlQuery;
if(SortField.Le ngth>0)
{sSqlQuery = "SELECT * FROM "+sDataTableNam e+" ORDER BY "+SortField ;}
else
{sSqlQuery = "SELECT * FROM "+sDataTableNam e;}

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

System.Data.Sql Client.SqlConne ction oConnection = HERE YOU NEED TO CREATE
A CONNECTION TO NORTHWIND

System.Data.Sql Client.SqlComma nd oCommand = new
System.Data.Sql Client.SqlComma nd(sSqlQuery, oConnection);
System.Data.Sql Client.SqlDataR eader oDataReader =
oCommand.Execut eReader();

System.Web.UI.W ebControls.Temp lateColumn oTemplateColumn ;
oTemplateColumn = new TemplateColumn( );
//oTemplateColumn .SortExpression = oDataReader.Get Name(0);
oTemplateColumn .HeaderTemplate = new
DataGridTemplat e(ListItemType. Header, oDataReader.Get Name(0));
oTemplateColumn .ItemTemplate = new DataGridTemplat e(ListItemType. Item,
oDataReader.Get Name(0));

MyDataGrid.Colu mns.Add(oTempla teColumn);
MyDataGrid.Data Source = oDataReader;
MyDataGrid.Data Bind();

oDataReader.Clo se();
oConnection.Clo se();
}

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

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

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

public DataGridTemplat e(ListItemType type, string colname)
{
templateType = type;
columnName = colname;
}
public void InstantiateIn(S ystem.Web.UI.Co ntrol container)
{
Label lb;
switch(template Type)
{
case ListItemType.He ader:
LinkButton oLinkButton = new LinkButton();
oLinkButton.Tex t = "<B>"+columnNam e+"</B>";
oLinkButton.ID = "SortLink";
oLinkButton.Com mandName = "sort";
oLinkButton.Com mandArgument = columnName;
// oLinkButton.Com mand+= new
System.Web.UI.W ebControls.Comm andEventHandler (OnSortCommand) ;
container.Contr ols.Add(oLinkBu tton); //adds the Control to the Controls
collection of the parent control
break;
case ListItemType.It em:
lb = new Label();
lb.DataBinding += new EventHandler(Te mplateControl_D ataBinding);
container.Contr ols.Add(lb);
break;
case ListItemType.Fo oter:
lb = new Label();
lb.Text = "<I>" + columnName + "</I>";
container.Contr ols.Add(lb);
break;
}
}
private void TemplateControl _DataBinding(ob ject sender,System.E ventArgs e)
{
DataGridItem container;
Label oLabel;
oLabel = (Label) sender;
container = (DataGridItem) oLabel.NamingCo ntainer;
oLabel.Text += DataBinder.Eval (container.Data Item, columnName);
}
}
}
Any help on this would be great.

Thanks in advance.

Nov 16 '05 #1
1 8901
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 InitializeCompo nent 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******** *****@TK2MSFTNG P12.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
programmaticall y (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="Web Form1.aspx.cs" AutoEventWireup ="false" Inherits="Admin _Interface03.We bForm1" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>WebForm1 </title>
<meta name="GENERATOR " Content="Micros oft Visual Studio .NET 7.1">
<meta name="CODE_LANG UAGE" Content="C#">
<meta name="vs_defaul tClientScript" content="JavaSc ript">
<meta name="vs_target Schema"
content="http://schemas.microso ft.com/intellisense/ie5">
</HEAD>
<body MS_POSITIONING= "GridLayout ">
<form id="Form1" method="post" runat="server">
<ASP:DATAGRID
id="MyDataGrid "
runat="server"
HeaderStyle-ForeColor="blac k"
HeaderStyle-BackColor="#ccc ccc"
Font-Size="8pt"
Font-Name="Verdana"
CellPadding="3" >
<Columns>
<asp:BoundColum n HeaderText="Sor table" DataField="Empl oyeeID"
SortExpression= "EmployeeID " />
<asp:BoundColum n HeaderText="Not Sortable" DataField="Birt hDate" />
<asp:TemplateCo lumn>
<HeaderTemplate >
<asp:LinkButt on id="SortButton1 " runat="server" CommandName="so rt" CommandArgument ="LastName">Lin kButton</asp:LinkButton>
</HeaderTemplate>
<ItemTemplate >
<asp:Label runat="server" Text='<%# DataBinder.Eval (Container,
"DataItem.LastN ame") %>' ID="Label1"/>
</ItemTemplate>
</asp:TemplateCol umn>
</Columns>
</ASP:DATAGRID>
</form>
</body>
</HTML>

code behind:

using System;
using System.Collecti ons;
using System.Componen tModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.Sess ionState;
using System.Web.UI;
using System.Web.UI.W ebControls;
using System.Web.UI.H tmlControls;
namespace Admin_Interface 03
{
public class WebForm1 : System.Web.UI.P age
{
private string sDataTableName = "Employees" ;
private string SortField = "";
protected System.Web.UI.W ebControls.Data Grid MyDataGrid;

private void Page_Load(objec t sender, System.EventArg s e)
{

MyDataGrid.Auto GenerateColumns = false;
MyDataGrid.Enab leViewState = true;

MyDataGrid.Allo wSorting = true;
MyDataGrid.Sort Command += new
System.Web.UI.W ebControls.Data GridSortCommand EventHandler(My DataGrid_Sort);
MyDataGrid.Show Header = true;
MyDataGrid.Show Footer = true;
MyDataGrid.Hori zontalAlign = HorizontalAlign .Center;
MyDataGrid.Alte rnatingItemStyl e.BackColor =
System.Drawing. Color.FromName( "#F1F1F1");
MyDataGrid.Cell Padding = 3;
MyDataGrid.Back Color = System.Drawing. Color.FromName( "#FFFFFF"); MyDataGrid.Widt h = Unit.Pixel(400) ;
MyDataGrid.Grid Lines = GridLines.Both;
MyDataGrid.Bord erWidth = Unit.Pixel(4);
MyDataGrid.Bord erStyle = BorderStyle.Sol id;
MyDataGrid.Bord erColor = System.Drawing. Color.FromName( "#C4C2C2");
MyDataGrid.Head erStyle.Font.Si ze = FontUnit.Point( 8);
MyDataGrid.Head erStyle.BackCol or =
System.Drawing. Color.FromName( "#F3F1F1");
MyDataGrid.Item Style.BackColor =
System.Drawing. Color.FromName( "#FFFFFF");

if (!IsPostBack)
{
Bind_Grid();
}
}
public void MyDataGrid_Sort (Object sender, DataGridSortCom mandEventArgs e) {
SortField = (string)e.SortE xpression;//OR SortField =
e.SortExpressio n.ToString();
Response.Write( "MyDataGrid_Sor t-SortField="+Sor tField+"<br>");
Bind_Grid();
}
public void Bind_Grid()
{
Response.Write( "SortField="+So rtField+"<br>") ;

string sSqlQuery;
if(SortField.Le ngth>0)
{sSqlQuery = "SELECT * FROM "+sDataTableNam e+" ORDER BY "+SortField ;}
else
{sSqlQuery = "SELECT * FROM "+sDataTableNam e;}

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

System.Data.Sql Client.SqlConne ction oConnection = HERE YOU NEED TO CREATE A CONNECTION TO NORTHWIND

System.Data.Sql Client.SqlComma nd oCommand = new
System.Data.Sql Client.SqlComma nd(sSqlQuery, oConnection);
System.Data.Sql Client.SqlDataR eader oDataReader =
oCommand.Execut eReader();

System.Web.UI.W ebControls.Temp lateColumn oTemplateColumn ;
oTemplateColumn = new TemplateColumn( );
//oTemplateColumn .SortExpression = oDataReader.Get Name(0);
oTemplateColumn .HeaderTemplate = new
DataGridTemplat e(ListItemType. Header, oDataReader.Get Name(0));
oTemplateColumn .ItemTemplate = new DataGridTemplat e(ListItemType. Item,
oDataReader.Get Name(0));

MyDataGrid.Colu mns.Add(oTempla teColumn);
MyDataGrid.Data Source = oDataReader;
MyDataGrid.Data Bind();

oDataReader.Clo se();
oConnection.Clo se();
}

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

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

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

public DataGridTemplat e(ListItemType type, string colname)
{
templateType = type;
columnName = colname;
}
public void InstantiateIn(S ystem.Web.UI.Co ntrol container)
{
Label lb;
switch(template Type)
{
case ListItemType.He ader:
LinkButton oLinkButton = new LinkButton();
oLinkButton.Tex t = "<B>"+columnNam e+"</B>";
oLinkButton.ID = "SortLink";
oLinkButton.Com mandName = "sort";
oLinkButton.Com mandArgument = columnName;
// oLinkButton.Com mand+= new
System.Web.UI.W ebControls.Comm andEventHandler (OnSortCommand) ;
container.Contr ols.Add(oLinkBu tton); //adds the Control to the Controls collection of the parent control
break;
case ListItemType.It em:
lb = new Label();
lb.DataBinding += new EventHandler(Te mplateControl_D ataBinding);
container.Contr ols.Add(lb);
break;
case ListItemType.Fo oter:
lb = new Label();
lb.Text = "<I>" + columnName + "</I>";
container.Contr ols.Add(lb);
break;
}
}
private void TemplateControl _DataBinding(ob ject sender,System.E ventArgs e) {
DataGridItem container;
Label oLabel;
oLabel = (Label) sender;
container = (DataGridItem) oLabel.NamingCo ntainer;
oLabel.Text += DataBinder.Eval (container.Data Item, 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
7898
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 header of the datagrid in the "ItemDataBound" method of the grid. However, once, they are added in the grid, i seem to lose the event handler for the...
3
3344
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 appearing on the existing column headers, and the text gets blurred with the painting of the column text along with the adjacent width 0 column. Anybody,...
0
1700
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 header, I'm intercepting the header click and "telling" it to sort the dataview using col_sort. But for some reason, the "return" is not being...
0
1811
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 sorting-hyperlink) a textbox. When my user clicks on a sort-hyperlink, I want to sort that column, but I also want to combine that with a rowfilter. That rowfilter...
11
2128
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 populate the data if !postback.
2
6384
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
3526
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 can get this to work; however, the column header on the datagrid is not a link/sortable. What am I missing? Thanks in advance.
4
2903
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
5364
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 GridView1_RowCreated(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.Header) {
0
7784
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7705
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8033
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8077
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6426
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5601
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5294
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3734
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
1044
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.