Dynamic Bound Columns OnSortCommand not called (Solution)

  • Thread starter Thread starter Chad Devine
  • Start date Start date
C

Chad Devine

Alright, I am posting my solution to a problem I've been having. I have
finally found the answer, and it took me a while so I thought I'd
provide the final solution here, since it may be benificial to others
and because I had to search for the solution (not the problem) in order
to find a working one.

I had a datagrid that wasn't sorting, the onsortcommand seemed as
though it wasn't being called, and I had dynamically bound columns in
the page_load sub. That was the big mistake.

Apparently, in order for the sortcommand to work correctly, you need to
bound your columns in a different sub, the page_init event sub. Once
you successfully do this, all is well. After doing a few very specific
searches I found this answer (in a rather vague form) on usenet.

The page_init sub runs before the page_load sub is run, and is only run
once when the page is first loaded, not on every page load.

------------
The code should look like:
Sub Page_Init(Sender As Object, E As EventArgs)
'Don't forget to open a sql connection here, and fill the dataset.

objDataTable = objDataSet.Tables(0)
For i = 0 To objDataTable.Columns.Count - 1
objCol = New BoundColumn()
objCol.HeaderText = objDataTable.Columns(i).ColumnName
objCol.DataField = objDataTable.Columns(i).ColumnName
objCol.SortExpression = objDataTable.Columns(i).ColumnName
DataGrid1.Columns.Add(objCol)
Next

End Sub

Some settings in the datagrid:
AutoGenerateColumns="False"
OnSortCommand="SQLDataGrid_SortCommand"
AllowSorting="True"
 
Or you could do this:

private page_load()
{
if ( !Page.IsPostBack)
{
//Build Dynamic columns here
}
}

You are only supposed to build (bind) your columns once, not everytime the
page_load event is called.

ENJOY !
 

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

Back
Top