Was having great fun today trying to get a datagrid to fire its ItemCommand event. Eventually managed to get it working but while on a search mission in Google it seemed many others had the same problem, so I thought I’d blog about it!
Sharepoint Webparts are like ASP.NET server controls where you have to build them up in completely in code, no user interface to drag and drop controls. Anyway back to the datagrid. I was creating the datagrid, adding the event handler, adding a button column, pretty much everything correctly, or so I thought. When clicking on a button though the page and control were doing a postback, but the ItemCommand event was not firing. The error I made turned out to be where I loaded and bound the data. I had it in the RenderWebPart method, whereas in effect it should have been done in the CreateChildControls method. Here’s the code:
protected DataGrid dgSubscriptions;
protected override void RenderWebPart(HtmlTextWriter output)
{
EnsureChildControls();
dgSubscriptions.RenderControl(output);
}
protected override void CreateChildControls()
{
base.CreateChildControls ();
dgSubscriptions = new DataGrid();
dgSubscriptions.ItemCommand += new DataGridCommandEventHandler(dgSubscriptions_ItemCommand);
ButtonColumn btn = new ButtonColumn();
btn.HeaderText = "test2";
btn.ButtonType = ButtonColumnType.PushButton;
btn.DataTextField = "Name";
btn.CommandName = "test";
dgSubscriptions.Columns.Add(btn);
Controls.Add(dgSubscriptions);
loadDataGrid();
}
private void loadDataGrid()
{
// load data and bind to grid...
}
private void dgSubscriptions_ItemCommand(object source, DataGridCommandEventArgs e)
{
string test = "DataGrid was clicked!";
}
Hope this helps someone.
No comments:
Post a Comment