SortCommand events not being caught

T

Tim Mulholland

I have a datagrid on one of my pages. I generate the columns that are in
this datagrid at runtime, including setting the SortCommand text.

When a user clicks on the link in the header to sort by that column, the
page posts back (and i can catch the Page_Load event) but the SortCommand
event handler is never reached.

I've double checked to make sure the attaching of the event handler is
happening properly, and all of that. The code is just never being executed.

I'm sure i'm just missing something silly.

Ideas?

Thanks in advance,

Tim
 
S

Steven Cheng[MSFT]

Hi Tim,

From the you description, you used a webform datagrid(with allowSorting as
true) and you generate some columns which need sorting at runtime into the
datagrid. However, you found that at runtime, when clicking the sorting
link, the page was posted back ,but the datagrid's sort event wasn't be
fired, yes?

As for this problem, I doubt that whether it is caused by the event handler
not being registerd correctly. Do you register the
datagrid 's sortcommand handler statically or dynamically at runtime? For
example:

this.dgFire.SortCommand += new
System.Web.UI.WebControls.DataGridSortCommandEventHandler(this.dgFire_SortCo
mmand);

If you add the event handler at runtime ( in page init or page_load), do
you add it every time the page is loaded( not only firsttime)? If not , the
event handler will be lost when the page is posted back. In other words,
the page will still be posted back when clicking the sort link, but the
serverside's handler will never be hited.
I've attached a test page to show the behavior I mentioned above in this
message, please refer to it to see whether this is the cause of your
problem.

In addition, if the problem is caused by anything else, would you please
provide some further code on your page so that I can help to do some
further research on my side? Thanks.


Regards,

Steven Cheng
Microsoft Online Support

Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)

Get Preview at ASP.NET whidbey
http://msdn.microsoft.com/asp.net/whidbey/default.aspx
 
J

Jos

Tim Mulholland said:
I have a datagrid on one of my pages. I generate the columns that are in
this datagrid at runtime, including setting the SortCommand text.

When a user clicks on the link in the header to sort by that column, the
page posts back (and i can catch the Page_Load event) but the SortCommand
event handler is never reached.

I've double checked to make sure the attaching of the event handler is
happening properly, and all of that. The code is just never being
executed.


I seem to recall having this problem when I bound a datagrid with a
datareader.
You need to bind the datagrid with a dataset in order to have sorting.
 
T

Tim Mulholland

I'm binding to a DataTable

Jos said:
executed.


I seem to recall having this problem when I bound a datagrid with a
datareader.
You need to bind the datagrid with a dataset in order to have sorting.
 
T

Tim Mulholland

I register the eventhandler at design time, using the VS property window for
the datagrid.
Thus the code is in the InitializeComponent() function.
I am unable to verify whether its set or not at runtime, because checking
dgContacts.SortCommand comes up as an error saying it doesn't exist and
dgContacts.EventSortCommand comes up as just being a System.Object, with no
other data.

If i check the Request.Form["__EVENTTARGET"] property, i get (as an example)
'dgContacts:_ctl1:_ctl1 which roughly coincides to the link i clicked on
(javascript:__doPostBack('dgContacts$_ctl1$_ctl1','')) - and since the
__doPostBack() function does a split('$').join(':') then this is what i
expect to see.

But still, the event is never fired.

The datagrid shows up on the page, but without the columns i'm adding
dymanically. It seems to still have the same datasource as it did
originally, just the columns are shown as if my code to add more was never
executed (some are there at design time, the majority are added at runtime).

I'm going to try to see if i can create a page with alot less code that
duplicates this error. I'll let you know if i come up with something.

Thanks for your help so far,

Tim
 
T

Tim Mulholland

I think the following page duplicates the problem i'm having. At least, it
duplicates it for me, i can't guarantee you'll see anything similar
result-wise.


****Begin testdatagrid.aspx****

<%@ Page language="c#" Codebehind="testdatagrid.aspx.cs"
AutoEventWireup="false" Inherits="ERT.CRM.testdatagrid" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<html>
<head>
<title>testdatagrid</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="dgOrders" runat="server" gridlines="Vertical"
cellpadding="3" backcolor="White"
borderwidth="1px" borderstyle="None" bordercolor="#999999"
visible="False" autogeneratecolumns="False"
allowsorting="True" cssclass="DataGrid-Header-Cell">
<selecteditemstyle font-bold="True" forecolor="White"
backcolor="#008A8C"></selecteditemstyle>
<alternatingitemstyle backcolor="Gainsboro"></alternatingitemstyle>
<itemstyle backcolor="#EEEEEE"></itemstyle>
<headerstyle font-bold="True" forecolor="White"
cssclass="DataGrid-Header"></headerstyle>
<footerstyle forecolor="Black" backcolor="#CCCCCC"></footerstyle>
<columns>
<asp:buttoncolumn text="View" commandname="Item"></asp:buttoncolumn>
<asp:boundcolumn visible="False" datafield="TheID"
headertext="TheID"></asp:boundcolumn>
</columns>
<pagerstyle horizontalalign="Center" forecolor="Black"
backcolor="#999999" mode="NumericPages"></pagerstyle>
</asp:datagrid>
</form>
</body>
</html>

****End testdatagrid.aspx****

****Begin testdatagrid.aspx.cs****

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 ERT.CRM
{
/// <summary>
/// Summary description for testdatagrid.
/// </summary>
public class testdatagrid : System.Web.UI.Page
{
protected System.Web.UI.WebControls.DataGrid dgOrders;

private string strSQL = "SELECT * FROM Employees";

private void Page_Load(object sender, System.EventArgs e)
{
if (!IsPostBack)
{
SetupOrders(strSQL);
}
}

private void dgOrders_SortCommand(object source,
System.Web.UI.WebControls.DataGridSortCommandEventArgs e)
{
strSQL += " ORDER BY " + e.SortExpression;
SetupOrders(strSQL);
}

private void SetupOrders(string s)
{
dgOrders.Visible = true;
dgOrders.DataSource = Data.GetDataSetNow(s);
foreach (System.Data.DataColumn dc in
((DataSet)dgOrders.DataSource).Tables[0].Columns)
{
if (dc.ColumnName == "TheID") continue;
System.Web.UI.WebControls.BoundColumn bc = new BoundColumn();
bc.DataField = dc.ColumnName;
bc.HeaderText = dc.ColumnName;
bc.SortExpression = dc.ColumnName + " ASC";
bc.Visible = true;
dgOrders.Columns.Add(bc);
}
dgOrders.DataBind();
}

#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.dgOrders.SortCommand += new
System.Web.UI.WebControls.DataGridSortCommandEventHandler(this.dgOrders_Sort
Command);
this.Load += new System.EventHandler(this.Page_Load);

}
#endregion
}
}

****End testdatagrid.aspx.cs****
 
T

Tim Mulholland

in doing some more testing,i've discovered that the problem DOES NOT occur,
if i set AutogenerateColumns to true and avoid executing my code that
manually builds the columns.
If i then set it back to false and run my code, the problem reoccurs.

So it seems like it might be connected with that.

Tim Mulholland said:
I think the following page duplicates the problem i'm having. At least, it
duplicates it for me, i can't guarantee you'll see anything similar
result-wise.


****Begin testdatagrid.aspx****

<%@ Page language="c#" Codebehind="testdatagrid.aspx.cs"
AutoEventWireup="false" Inherits="ERT.CRM.testdatagrid" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<html>
<head>
<title>testdatagrid</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="dgOrders" runat="server" gridlines="Vertical"
cellpadding="3" backcolor="White"
borderwidth="1px" borderstyle="None" bordercolor="#999999"
visible="False" autogeneratecolumns="False"
allowsorting="True" cssclass="DataGrid-Header-Cell">
<selecteditemstyle font-bold="True" forecolor="White"
backcolor="#008A8C"></selecteditemstyle>
<alternatingitemstyle backcolor="Gainsboro"></alternatingitemstyle>
<itemstyle backcolor="#EEEEEE"></itemstyle>
<headerstyle font-bold="True" forecolor="White"
cssclass="DataGrid-Header"></headerstyle>
<footerstyle forecolor="Black" backcolor="#CCCCCC"></footerstyle>
<columns>
<asp:buttoncolumn text="View" commandname="Item"></asp:buttoncolumn>
<asp:boundcolumn visible="False" datafield="TheID"
headertext="TheID"></asp:boundcolumn>
</columns>
<pagerstyle horizontalalign="Center" forecolor="Black"
backcolor="#999999" mode="NumericPages"></pagerstyle>
</asp:datagrid>
</form>
</body>
</html>

****End testdatagrid.aspx****

****Begin testdatagrid.aspx.cs****

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 ERT.CRM
{
/// <summary>
/// Summary description for testdatagrid.
/// </summary>
public class testdatagrid : System.Web.UI.Page
{
protected System.Web.UI.WebControls.DataGrid dgOrders;

private string strSQL = "SELECT * FROM Employees";

private void Page_Load(object sender, System.EventArgs e)
{
if (!IsPostBack)
{
SetupOrders(strSQL);
}
}

private void dgOrders_SortCommand(object source,
System.Web.UI.WebControls.DataGridSortCommandEventArgs e)
{
strSQL += " ORDER BY " + e.SortExpression;
SetupOrders(strSQL);
}

private void SetupOrders(string s)
{
dgOrders.Visible = true;
dgOrders.DataSource = Data.GetDataSetNow(s);
foreach (System.Data.DataColumn dc in
((DataSet)dgOrders.DataSource).Tables[0].Columns)
{
if (dc.ColumnName == "TheID") continue;
System.Web.UI.WebControls.BoundColumn bc = new BoundColumn();
bc.DataField = dc.ColumnName;
bc.HeaderText = dc.ColumnName;
bc.SortExpression = dc.ColumnName + " ASC";
bc.Visible = true;
dgOrders.Columns.Add(bc);
}
dgOrders.DataBind();
}

#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.dgOrders.SortCommand += new
System.Web.UI.WebControls.DataGridSortCommandEventHandler(this.dgOrders_Sort
Command);
this.Load += new System.EventHandler(this.Page_Load);

}
#endregion
}
}

****End testdatagrid.aspx.cs****
 
S

Steven Cheng[MSFT]

Hi Tim,

Thanks for your followup. From the code you provided, I've got that the
problem is caused by the columns that be added dynamically into the
datagrid according to the columns in the datatable you retrieved from
database. In ASP.NET webform, if we need to dynamically add control onto
it, we need to add it every time the page is request( every time in the
Page_Load or Page_Init). If we only add it when (!IsPostBack), then when
the page is posted back(hit some submit button) , the dynamically added
control will disappear. For example, if we add the following code in
Page_Load to add a textbox in a parent container control:

if(!IsPostBack)
{
TextBox txtDynamic = new TextBox();
txtDynamic.ID = "txtDynamic";
this.Controls.Add(txtDynamic);
}

Then, if the page is postedback, the textbox will disappear.

So the problem in our issue is also caused by this, because you add the
columns dynamically in the
if(!IsPostBack)
{
...
}
block , then when we hit the "sort link" to fire the datagrid's
SortCommand( page is posted back), the columns disappeared, and apparently
the SortCommand won't be fired( because the event mapping has been lost).

Here are two means to resolve it:
1. To initally add enough boundcolumns at design time and set their visible
as "false". Then, at runtime set the proper columns' visible as true and
modify their attrbutes.

2. Still add the columns add runtime, but need to add them every time page
is requested(no matter postback or not). By this means, you need to store
the columns' information need to readded in a proper place(session, or a
hidden field).

Here is a demo page which including the both means above, please check it
out and if you have anything unclear, please feel free to post here.

====================aspx page ====================
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>SortColumnGrid</title>
<meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR">
<meta content="C#" name="CODE_LANGUAGE">
<meta content="JavaScript" name="vs_defaultClientScript">
<meta content="http://schemas.microsoft.com/intellisense/ie5"
name="vs_targetSchema">
</HEAD>
<body>
<form id="Form1" method="post" runat="server">
<table width="100%" align="center">
<tr>
<td>This Grid Add Columns Dynamicaly:<br>
<asp:datagrid id="dgDynamic" runat="server" AllowSorting="True"
AutoGenerateColumns="False"></asp:datagrid><INPUT id="hdColumns"
type="hidden" runat="server"></td>
</tr>
<tr>
<td>This Grid Add Columns Staticaly<br>
<asp:datagrid id="dgStatic" runat="server" AllowSorting="True"
AutoGenerateColumns="False">
<Columns>
<asp:BoundColumn Visible="False" HeaderText="c1"></asp:BoundColumn>
<asp:BoundColumn Visible="False" HeaderText="c2"></asp:BoundColumn>
<asp:BoundColumn Visible="False" HeaderText="c3"></asp:BoundColumn>
<asp:BoundColumn Visible="False" HeaderText="c4"></asp:BoundColumn>
<asp:BoundColumn Visible="False" HeaderText="c5"></asp:BoundColumn>
<asp:BoundColumn Visible="False" HeaderText="c6"></asp:BoundColumn>
<asp:BoundColumn Visible="False" HeaderText="c7"></asp:BoundColumn>
<asp:BoundColumn Visible="False" HeaderText="c8"></asp:BoundColumn>
<asp:BoundColumn Visible="False" HeaderText="c9"></asp:BoundColumn>
<asp:BoundColumn Visible="False" HeaderText="c10"></asp:BoundColumn>
</Columns>
</asp:datagrid></td>
</tr>
</table>
</form>
</body>
</HTML>

=================code behind page class============
public class SortColumnGrid : System.Web.UI.Page
{
protected System.Web.UI.WebControls.DataGrid dgDynamic;
protected System.Web.UI.HtmlControls.HtmlInputHidden hdColumns;
protected System.Web.UI.WebControls.DataGrid dgStatic;

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

}

protected void BindStaticColumns()
{
DataTable tb = GetDataSource();

int icol = 0;
foreach(System.Data.DataColumn dc in tb.Columns)
{
BoundColumn bc = (BoundColumn)dgStatic.Columns[icol];
bc.DataField = dc.ColumnName;
bc.HeaderText = dc.ColumnName;
bc.SortExpression = dc.ColumnName + " ASC";
bc.Visible = true;
dgStatic.Columns[icol].Visible = true;
icol++;
}

dgStatic.DataSource = tb;
dgStatic.DataBind();

}

protected void BindDynamicColumns()
{
DataTable tb = GetDataSource();
string[] cols = new string[tb.Columns.Count];
int icol = 0;
foreach(System.Data.DataColumn dc in tb.Columns)
{
System.Web.UI.WebControls.BoundColumn bc = new BoundColumn();
bc.DataField = dc.ColumnName;
bc.HeaderText = dc.ColumnName;
bc.SortExpression = dc.ColumnName + " ASC";
bc.Visible = true;
dgDynamic.Columns.Add(bc);

cols[icol] = dc.ColumnName;
icol++;
}

dgDynamic.DataSource = tb;
dgDynamic.DataBind();

hdColumns.Value = string.Join("#",cols);
}

protected void ReSetupDynamicColumns()
{
char[] flags = {'#'};
string hdColumns = Request.Form["hdColumns"];
string[] cols = hdColumns.Split(flags);
for(int i=0;i<cols.Length;i++)
{
System.Web.UI.WebControls.BoundColumn bc = new BoundColumn();
bc.DataField = cols;
bc.HeaderText = cols;
bc.SortExpression = cols + " ASC";
bc.Visible = true;
dgDynamic.Columns.Add(bc);
}
}

protected DataTable GetDataSource()
{
DataTable tb = new DataTable();
tb.Columns.Add("index");
tb.Columns.Add("name");
tb.Columns.Add("price",typeof(double));

DataRow dr = null;
bool[] flags = {true,false};
for(int i=1;i<=4;++i)
{
dr = tb.NewRow();
dr["index"] = i.ToString();
dr["name"] = "Name" + i.ToString();
dr["price"] = 3.434 * (i%3 +1);

tb.Rows.Add(dr);
}

return tb;
}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
InitializeComponent();
base.OnInit(e);

if(!IsPostBack)
{
BindStaticColumns();
BindDynamicColumns();
}
else
{
ReSetupDynamicColumns();
}
}

private void InitializeComponent()
{
this.dgDynamic.SortCommand += new
System.Web.UI.WebControls.DataGridSortCommandEventHandler(this.dgDynamic_Sor
tCommand);
this.dgStatic.SortCommand += new
System.Web.UI.WebControls.DataGridSortCommandEventHandler(this.dgStatic_Sort
Command);
this.Load += new System.EventHandler(this.Page_Load);

}
#endregion

private void dgStatic_SortCommand(object source,
System.Web.UI.WebControls.DataGridSortCommandEventArgs e)
{
Response.Write("<br>dgStatic's SortCommand is fired at: " +
DateTime.Now.ToLongTimeString());
Response.Write("<br>SortExpression: " + e.SortExpression );
}

private void dgDynamic_SortCommand(object source,
System.Web.UI.WebControls.DataGridSortCommandEventArgs e)
{
Response.Write("<br>dgDynamic's SortCommand is fired at: " +
DateTime.Now.ToLongTimeString());
Response.Write("<br>SortExpression: " + e.SortExpression );
}

}
============================================================



Regards,

Steven Cheng
Microsoft Online Support

Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)

Get Preview at ASP.NET whidbey
http://msdn.microsoft.com/asp.net/whidbey/default.aspx
 
R

Ravichandran J.V.

You are probably not attaching it with the
+=

or

you have not set it in the HTML section
<onSortCommand="sortCommandProcedure">

with regards,


J.V.Ravichandran
- http://www.geocities.com/
jvravichandran
- http://www.411asp.net/func/search?
qry=Ravichandran+J.V.&cob=aspnetpro
- http://www.southasianoutlook.com
- http://www.MSDNAA.Net
- http://www.csharphelp.com
- http://www.poetry.com/Publications/
display.asp?ID=P3966388&BN=999&PN=2
- Or, just search on "J.V.Ravichandran"
at http://www.Google.com
 
T

Tim Mulholland

Ahh, ok this all makes sense now.
Thanks so much for your explanation.
I got it working now with no major problems.
I appreciate your help,

Tim

Steven Cheng said:
Hi Tim,

Thanks for your followup. From the code you provided, I've got that the
problem is caused by the columns that be added dynamically into the
datagrid according to the columns in the datatable you retrieved from
database. In ASP.NET webform, if we need to dynamically add control onto
it, we need to add it every time the page is request( every time in the
Page_Load or Page_Init). If we only add it when (!IsPostBack), then when
the page is posted back(hit some submit button) , the dynamically added
control will disappear. For example, if we add the following code in
Page_Load to add a textbox in a parent container control:

if(!IsPostBack)
{
TextBox txtDynamic = new TextBox();
txtDynamic.ID = "txtDynamic";
this.Controls.Add(txtDynamic);
}

Then, if the page is postedback, the textbox will disappear.

So the problem in our issue is also caused by this, because you add the
columns dynamically in the
if(!IsPostBack)
{
..
}
block , then when we hit the "sort link" to fire the datagrid's
SortCommand( page is posted back), the columns disappeared, and apparently
the SortCommand won't be fired( because the event mapping has been lost).

Here are two means to resolve it:
1. To initally add enough boundcolumns at design time and set their visible
as "false". Then, at runtime set the proper columns' visible as true and
modify their attrbutes.

2. Still add the columns add runtime, but need to add them every time page
is requested(no matter postback or not). By this means, you need to store
the columns' information need to readded in a proper place(session, or a
hidden field).

Here is a demo page which including the both means above, please check it
out and if you have anything unclear, please feel free to post here.

====================aspx page ====================
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>SortColumnGrid</title>
<meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR">
<meta content="C#" name="CODE_LANGUAGE">
<meta content="JavaScript" name="vs_defaultClientScript">
<meta content="http://schemas.microsoft.com/intellisense/ie5"
name="vs_targetSchema">
</HEAD>
<body>
<form id="Form1" method="post" runat="server">
<table width="100%" align="center">
<tr>
<td>This Grid Add Columns Dynamicaly:<br>
<asp:datagrid id="dgDynamic" runat="server" AllowSorting="True"
AutoGenerateColumns="False"></asp:datagrid><INPUT id="hdColumns"
type="hidden" runat="server"></td>
</tr>
<tr>
<td>This Grid Add Columns Staticaly<br>
<asp:datagrid id="dgStatic" runat="server" AllowSorting="True"
AutoGenerateColumns="False">
<Columns>
<asp:BoundColumn Visible="False" HeaderText="c1"></asp:BoundColumn>
<asp:BoundColumn Visible="False" HeaderText="c2"></asp:BoundColumn>
<asp:BoundColumn Visible="False" HeaderText="c3"></asp:BoundColumn>
<asp:BoundColumn Visible="False" HeaderText="c4"></asp:BoundColumn>
<asp:BoundColumn Visible="False" HeaderText="c5"></asp:BoundColumn>
<asp:BoundColumn Visible="False" HeaderText="c6"></asp:BoundColumn>
<asp:BoundColumn Visible="False" HeaderText="c7"></asp:BoundColumn>
<asp:BoundColumn Visible="False" HeaderText="c8"></asp:BoundColumn>
<asp:BoundColumn Visible="False" HeaderText="c9"></asp:BoundColumn>
<asp:BoundColumn Visible="False" HeaderText="c10"></asp:BoundColumn>
</Columns>
</asp:datagrid></td>
</tr>
</table>
</form>
</body>
</HTML>

=================code behind page class============
public class SortColumnGrid : System.Web.UI.Page
{
protected System.Web.UI.WebControls.DataGrid dgDynamic;
protected System.Web.UI.HtmlControls.HtmlInputHidden hdColumns;
protected System.Web.UI.WebControls.DataGrid dgStatic;

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

}

protected void BindStaticColumns()
{
DataTable tb = GetDataSource();

int icol = 0;
foreach(System.Data.DataColumn dc in tb.Columns)
{
BoundColumn bc = (BoundColumn)dgStatic.Columns[icol];
bc.DataField = dc.ColumnName;
bc.HeaderText = dc.ColumnName;
bc.SortExpression = dc.ColumnName + " ASC";
bc.Visible = true;
dgStatic.Columns[icol].Visible = true;
icol++;
}

dgStatic.DataSource = tb;
dgStatic.DataBind();

}

protected void BindDynamicColumns()
{
DataTable tb = GetDataSource();
string[] cols = new string[tb.Columns.Count];
int icol = 0;
foreach(System.Data.DataColumn dc in tb.Columns)
{
System.Web.UI.WebControls.BoundColumn bc = new BoundColumn();
bc.DataField = dc.ColumnName;
bc.HeaderText = dc.ColumnName;
bc.SortExpression = dc.ColumnName + " ASC";
bc.Visible = true;
dgDynamic.Columns.Add(bc);

cols[icol] = dc.ColumnName;
icol++;
}

dgDynamic.DataSource = tb;
dgDynamic.DataBind();

hdColumns.Value = string.Join("#",cols);
}

protected void ReSetupDynamicColumns()
{
char[] flags = {'#'};
string hdColumns = Request.Form["hdColumns"];
string[] cols = hdColumns.Split(flags);
for(int i=0;i<cols.Length;i++)
{
System.Web.UI.WebControls.BoundColumn bc = new BoundColumn();
bc.DataField = cols;
bc.HeaderText = cols;
bc.SortExpression = cols + " ASC";
bc.Visible = true;
dgDynamic.Columns.Add(bc);
}
}

protected DataTable GetDataSource()
{
DataTable tb = new DataTable();
tb.Columns.Add("index");
tb.Columns.Add("name");
tb.Columns.Add("price",typeof(double));

DataRow dr = null;
bool[] flags = {true,false};
for(int i=1;i<=4;++i)
{
dr = tb.NewRow();
dr["index"] = i.ToString();
dr["name"] = "Name" + i.ToString();
dr["price"] = 3.434 * (i%3 +1);

tb.Rows.Add(dr);
}

return tb;
}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
InitializeComponent();
base.OnInit(e);

if(!IsPostBack)
{
BindStaticColumns();
BindDynamicColumns();
}
else
{
ReSetupDynamicColumns();
}
}

private void InitializeComponent()
{
this.dgDynamic.SortCommand += new
System.Web.UI.WebControls.DataGridSortCommandEventHandler(this.dgDynamic_Sor
tCommand);
this.dgStatic.SortCommand += new
System.Web.UI.WebControls.DataGridSortCommandEventHandler(this.dgStatic_Sort
Command);
this.Load += new System.EventHandler(this.Page_Load);

}
#endregion

private void dgStatic_SortCommand(object source,
System.Web.UI.WebControls.DataGridSortCommandEventArgs e)
{
Response.Write("<br>dgStatic's SortCommand is fired at: " +
DateTime.Now.ToLongTimeString());
Response.Write("<br>SortExpression: " + e.SortExpression );
}

private void dgDynamic_SortCommand(object source,
System.Web.UI.WebControls.DataGridSortCommandEventArgs e)
{
Response.Write("<br>dgDynamic's SortCommand is fired at: " +
DateTime.Now.ToLongTimeString());
Response.Write("<br>SortExpression: " + e.SortExpression );
}

}
============================================================



Regards,

Steven Cheng
Microsoft Online Support

Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)

Get Preview at ASP.NET whidbey
http://msdn.microsoft.com/asp.net/whidbey/default.aspx
 
L

lien

In march 23, 04. Steven Cheng showed us how to do sortcommand for
datagrid created at run time (thank you) . What if I have mixed
static and dynamic columns? that is colunms added into static
datagrid at run time. How to associate these dynamic columns to
existing sortcommand we already have for static datagrid?
Thanks,
Lien

*-----------------------*
Posted at:
www.GroupSrv.com
*-----------------------*
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top