I am having a problem with a dynamically (programmatically) generated DataGrid. I am building the DataGrid in code using code like:
private void BindGrid()
strSql = strSelect + " " + strWhere + " " + strOrderBy;
SqlConnection conn = new SqlConnection(strConnect);
SqlDataAdapter da = new SqlDataAdapter(strSql, conn);
DataSet ds = new DataSet();
dg.DataSource = ds;
foreach(System.Data.DataColumn col in ds.Tables.Columns)
BoundColumn bc = new BoundColumn();
bc.DataField = col.ColumnName;
bc.SortExpression = col.ColumnName;
bc.HeaderText = col.ColumnName.Replace("_", " ");
// bunch of other code here
The problem occurs when I click a column heading to sort the grid - the grid disappears. I've set AutoGenerateColumns = false, and have attached a dg_SortCommand event to the grid but the SortCommand doesn't fire.
I've checked other websites concerning this problem, so I understand such issues as rebinding the grid, checking to make sure the added SortCommand event didn't "disappear" in InitializeComponent, adding an empty BoundColumn to the grid at design-time.
Right now, the only way I can get the SortCommand event to fire is to call BindGrid() inside Page_Load(), which recreates the grid, then the SortCommand event is fired, which retrieves the new sorting string (i.e. strOrderBy = "ORDER BY " + e.SortExpression), then call BindGrid() again using the newly set strOrderBy to order the results correctly. Thus, I'm making two calls to BindGrid(), which doesn't seem right, plus I get two sets of all my columns because I've added them twice.
So the real question is: How do you get the SortCommand event to fire when using dynamically generated columns without recreating the grid first, then allowing the SortCommand event to fire, then rebuilding the grid again using the new sort?
By the way, this is not at all a trivial question - I have not found a single solution anywhere on the internet for this type of problem. The real problem is that I'm not setting the columns at design-time. I had the grid working fine when I set up the columns at design-time using Property Builder. The sorting event fires just fine. It's when I start generating the columns in code that the problems start.