Custom DataGrid control in user control

Hi there,

I have created a custom datagrid control which i reference within a user control and it's corresponding code behind page. The problem I am encountering is that when I click on the paging buttons in the datagrid no event is fired, however if I reference the same control from a page everything works fine. I'm not sure where I am going wrong and would be greatful for any help that can be offered.
I have not posted the code here as there is quite a lot although should anyone feel that it would be helpful in them coming to a solution I would be more than willing to do so.
Cheers, Dan.
12/5/2002 3:20:28 PM 4216 articles. 0 followers. Follow

7 Replies

Similar Articles

[PageSpeed] 42

If you're trying to capture the events of the DataGrid in the Page...when it is hosted in a're gonna have problems. What you'll want to do is handle all the events in the UserControl aren't automatically bubbled up the control hierarchy. If you need to capture the events in the'll have to hook up your own routing scheme...basically by adding matching events in your UserControl that simply propagate the events from the datagrid to the page.

--- UserControl.ascx ---
<script language="C#">
public event EventHandler DeleteCommand;
protected virtual void OnDeleteCommand( EventArgs e )
if( DeleteCommand != null )
DeleteCommand( this, e );
private void DataGrid_DeleteCommand( object sender, EventArgs e )
OnDeleteCommand( e );

Paul Alexander
DeployLX|Licensing: Protect your .NET
CodeVeil: Assembly Encryption
12/5/2002 9:46:37 PM
Thanks for your quick reply, I have tried this today as I intially had all the event handlers in the custom control itself. The events that i am trying to catch are SortCommand and PageIndexChanged, however even after having moved the handlers in to the code behind of the user controls I am still encountering problems. As soon as I get in to work tomorrow i shall post some of the code to give you a better idea of how I am going about it.

Speak to you soon, Dan.
12/5/2002 10:00:02 PM
I was having exactly the same problem as Dan. So I moved the event handling into the usercontrol, with the result that the PageChanged events are caught. 

But not always correctly. I'll explain this with an example:
Initial Page Links:
1 2 3 4 5 ...
I click on ...
.... 6 7 8 9 10 ...
now, when I click on click on 7 I get thrown back to page 3 (8 to 4, 9 to 5, ... to 1)
this problem has been driving me nuts for quite a while now and I'd be very grateful if someone could point out a mistake (in coding or thinking).
code follows:

/// <summary>
/// Base DataGrid
/// </summary>
public class BsDataGrid : DataGrid
protected int _currentPageNumber = 1;
/// <summary>
/// Constructor
/// </summary>
public BsDataGrid()
// Standardeinstellunge für alle Grids
this.AutoGenerateColumns = false;
this.EnableViewState = true;

this.PageIndexChanged += new DataGridPageChangedEventHandler(MyPageIndexChanged);
this.AllowPaging = true;
this.AllowCustomPaging = false;
this.PagerStyle.Visible = true;
this.PageSize = 3;
this.PagerStyle.PageButtonCount = 5;
this.PagerStyle.Mode = PagerMode.NumericPages;
this.PagerStyle.CssClass = "myDataGridPagerStyle";
this.ItemStyle.CssClass= "myDataGridStyle";
this.AlternatingItemStyle.CssClass = "myDataGridStyleAlternate";

private void MyPageIndexChanged(object sender, DataGridPageChangedEventArgs e)
this.CurrentPageIndex = e.NewPageIndex;


/// <summary>
/// Composite Control with an instance of BsDataGrid
/// </summary>
public class PartyGrid : Panel
private BsDataGrid grid;
public PartyGrid()
grid = new UC.Grid.BsDataGrid();
grid.AllowPaging = true;
grid.EnableViewState = true;
// Add one simple bound Column
BoundColumn bc = new BoundColumn();
bc.DataField = "p_ID";

public override void DataBind()
// Get the Data from the Database
PartySearch search = new PartySearch();
search.iRoleType = 3;
DataTable parties = search.Search();
grid.DataSource = parties;
public Object DataSource
set {grid.DataSource = value;}


12/6/2002 8:13:36 AM
The actual probalem that I am encoutering is that the events aren't even recognised though - when I click on the next page link my datagrid simply dissapears. Even when I step through in VS.Net the event handlers appear not to be being fired. This really has me stumped - I've been looking at it this morning and am getting more and more frustrated.

I've included excerpts of the code below (let me know if there's anything else you want posting):
-- Custom control

public bool Populate(int intJurisdictionLevelID)
// before doing anything make sure the datagrid is viewable
if(base.Visible == false)
base.Visible = true;
// make sure the header is shown for the title
base.ShowHeader = true;
// set the defaults for the datagrid - make sure the datagrid is pageable and set the default page size, allow for sorting
base.AllowPaging = true;
// base.AllowCustomPaging = true;
base.PageSize = 25;
base.AllowSorting = true;
// add an event to the datagrid for itemCreated
base.ItemCreated += new System.Web.UI.WebControls.DataGridItemEventHandler(this.DataGrid_ItemCreated);
// base.PageIndexChanged += new System.Web.UI.WebControls.DataGridPageChangedEventHandler(this.DataGrid_PageChanged);
// base.SortCommand += new System.Web.UI.WebControls.DataGridSortCommandEventHandler(this.DataGrid_Sorted);
// make sure the columns are generated dynamically
base.AutoGenerateColumns = false;
// make sure that when this method is called the pager bar count is set to 0
_intPagerBar = 0;
// First get the heading for ranking column and the jurisdiction column
catch(System.Exception e)
_strErrorMessage = string.Format("Can't get indicator meta data for datagrid. Reason: {0}", e.Message);
return false;
// apply style to the header
base.HeaderStyle.CssClass = "colheading";

// Now add a bound column for the rank-position and the jurisdiction
System.Web.UI.WebControls.BoundColumn PositionColumn = new System.Web.UI.WebControls.BoundColumn();
PositionColumn.DataField = "Position";
PositionColumn.HeaderText = "Rank";
PositionColumn.SortExpression = "Position";
catch(System.Exception e)
_strErrorMessage = string.Format("Failed to create position column. Reason: {0}", e.Message);
return false;
System.Web.UI.WebControls.BoundColumn JurisdictionColumn = new System.Web.UI.WebControls.BoundColumn();
JurisdictionColumn.DataField = "JurisdictionName";
JurisdictionColumn.HeaderText = _arrJurisdictionLevelDetails[1];
JurisdictionColumn.SortExpression = "JurisdictionName";
catch(System.Exception e)
_strErrorMessage = string.Format("Failed to create JurisdictionName column. Reason: {0}", e.Message);
return false;
// Create the rest of the columns dependant on rank meta data
CreateColumns(_strRankingMetaDataXmlPath, intJurisdictionLevelID);
catch(System.Exception e)
_strErrorMessage = string.Format("Failed to create dynamic columns. Reason: {0}", e.Message);
return false;
// Add a column for the score and unfilteredrank
System.Web.UI.WebControls.BoundColumn ScoreColumn = new System.Web.UI.WebControls.BoundColumn();
ScoreColumn.DataField = "IndicatorValue";
ScoreColumn.HeaderText = _rankUnits;
ScoreColumn.SortExpression = "IndicatorValue";
System.Web.UI.WebControls.BoundColumn RankColumn = new System.Web.UI.WebControls.BoundColumn();
RankColumn.DataField = "NationalRank";
RankColumn.HeaderText = _rankColumnTitle;
// bind data
base.DataSource = LoadData(0);
int CurrentPage = base.VirtualItemCount;

return true;
// function to get the data for the rank table
public System.Data.DataSet LoadData(int StartPage)
LocalKnowledge.Data.Xml.XmlFunctions objXml = new LocalKnowledge.Data.Xml.XmlFunctions();
System.Data.DataSet ds = objXml.GetXmlFragmentAsDataset(_strRankingDataXmlPath, "//Rank");
objXml = null;
return ds;

-- User control

dgRanking.PageIndexChanged += new System.Web.UI.WebControls.DataGridPageChangedEventHandler(this.DataGrid_PageChanged);
public void DataGrid_PageChanged(object sender, System.Web.UI.WebControls.DataGridPageChangedEventArgs e)
dgRanking.Visible = true;
dgRanking.intPagerBar = 0;
dgRanking.CurrentPageIndex = e.NewPageIndex;
dgRanking.DataSource = dgRanking.LoadData(dgRanking.CurrentPageIndex);
12/6/2002 11:46:12 AM
Generally this mysterious dissappearing datagrid is caused when the grid is not bound on each request. You need to make sure that you bind the grid on each request to the page because the viewstate will not recreate the data source it has to be given to the grid on each request.
Paul Alexander
DeployLX|Licensing: Protect your .NET
CodeVeil: Assembly Encryption
12/7/2002 12:07:09 AM
I have similar issues. I created a kind of wrapper around the DataGrid control. The wrapper by itself works fine, but the issue comes up when I want to add the control programatically to a aspx page.

How can I propagate the pageindex changed events to the caller ?
8/8/2003 9:07:26 AM
Has any one found and answer to this question?

DeLeon English
Plano, Texas
9/9/2003 5:52:17 PM

Similar Artilces:

User Control VB.Net x Web Custom Control
I was thinking in create a user control in VB.Net, and use it in a Asp.Net as possible? So I thought about it is gonna be better than make a Web Custom Control, so i thought again, nope... But i need to know better because a don't have a progress bar in for example.... Could Somebody tell me about??? in a reallity i know the asnwer but i would like to explain by myself... Thank's Antonio...

Custom Controls or User Controls
Hi, I have to create a menu control and I am unable to decide between a custom control or user control.  Apart from the fact that a custom control can be inserted into the toolbox what are the other advantages and disadvantages of each like performance, and so on.  Plus how do I decide between the two. Thanks Arjuna. Hello Please refer to the KB article Overview of user controls vs. custom controls Hope it helps, JessicaJessica CaoSincerely,Microsoft Online Community Support“Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer...

User Controls and Custom Controls
what is Diff between User Controls and Custom Controls? User controls are asmx files, you can use them as a webpage, drag and drop as many controls you want and still user the user control to drop it into a form.Custom Controls are inherit from the control or used as composite control. You need to write the control by hand and override all the properties. They can be added into your toolbar.Hope this helpsCheersAlMy BlogMapStats.NETPlease click on 'Mark as Answer' if this post answered your question! Also... User Controls are generally application specific.  If you want...

user control and custom control
What is different between Web User Control and Web Custom Control?, EdMicrosoft MVP - ASP/ASP.NET I would suggest you to google the word "different between Web User Control and Web Custom Control" to get more informations and results...Regards,Vinz"Code, Beer and Music" that's my way of being a programmer!How to get your Forum Question Answered | Blog | CodeASP.NET Web custom controls are compiled components that run on the server and that encapsulate user-interface and other related functionality into reusable pack...

user control or custom control ?
i have datagrid which shows monthyear user control for each row. The month year user control has two drop down list. one is for year and other one is for month. So for each row in particular column i'll have that user control loaded. it works fine but ut takes lot of time in rendering when there are 200 rows. what would be the solution. will custom control help? Hi,Lax4u: Some tips i am not quite sure. First, you can disable the viewstate of the userControl to make it not load so many information in each postback and store the necessary in the global range. Second, Caching porting of th...

Custom User Controls v. Custom Web Controls
Hi! Is it better for me to begin coding my controls instead of just designing them? What would the benefits be? I meen, i seem to be able to get all i need from just putting stuff together on an ASCX file but i'm obviously missing a huge concept here... please explain! Hi, creating user controls is indeed easier than creating custom server controls because you can simply drag & drop other controls on the form, easily add events to it, ... Custom controls however are better when you want to reuse them in several other projects. I like to create custom controls for small, reusable com...

Custom Control within a Control Control
I am developing a custom controls that will render headers for different web sites. Within these controls, I want to place another custom control that will change the language. I created the language control and had it implement IPostBackDataHandler. This control works fine if I drag it on a new web form, but if I tell a header custom control to render it problems occur. The Language Selector custom control does not have a Page member anymore and the event handlers do not work. Does anyone have any experience with doing something similiar? Anyone have any suggestions? Thanks, ...

user control to user control
I have an aspx page that have a "Register" directive to two usercontrol called rptMaster.ascx and rptDetail.ascx. I'm trying to set up a Master-Detail relationship and wish for the rptMaster.ascx to trigger and event from a dropdownlist and for the rptDetail to be listening for DropDownList event. I believe I have gotten the events part okay with help from this articel but my declaration for a private statement to my rptMaster class is producing an error. I'm using beta 2 of and I 'm having trouble getting a reference TO ...

User Controls in User Controls?
I have the follow set up and it is throwing an error "Unhandled error loading module" ... is there some trick to this that I don't know?I have a project A that uses controls from project B (project B is just a project with all my user controls used through out other modules).  project A uses user control 1 from project B with out any issues at all - great.  But then I wanted to add user control 2 to user control 1 and that is when I get my error.  In fact I don't even have the user control 2 in user control 1, just when I put the register part into user control 1 is when it al...

User control in a user control
Hello all, I have created a user control with some checkboxes, and public properties to get the values of these checkboxes. I have also created a second user control using the first user control; this second control also access the public properties of the first one. My problem is when I implement the second control in an aspx page, if I click at runtime the checkboxes in the first control, I am able to access its public properties from the methods of the second control but the values of these properties are wrong. while at design time, I do not have this problem. Than...

User Control in a User Control
I have a first user control that contain a second user control. If I cahe the first user control can I still dynamically control the second one or it is cached with the first one therefore can not control it anymore? Thanks When your first control is cached, its rendered out and its output is stored in the cache. On every request to the page containing your control that can satisfy it from cache, the output will just simply be inserted - your first control will never be instantiated or run in that case, so the second one wont be either. Hope this helps,Mike VolodarskyProgram Manager...

How to access a user control from another user control in a Wizard control
My page has a wizard control and each step is a user control.  I could find the value of a control in step1 user control in the wizard page but not in step2 user control.From wizard.aspx.vb – it worksDim m_title As DropDownList = CType(Me.PersonalBox1.FindControl("ddlTitle1"), DropDownList) Question:How can I find the value of a control(textbox or dropdownlist)in step1 user control from step2 user control? I want to find “PersonalBox1.FindControl("ddlTitle1")” from Step2 AddressBox1. I have tried several ways to access it but no luck. From AddressBox.ascx.vb –...

User Controls not working if I put Validation controls in user control
Hi           I have validation controls(RequiredField Validator,RegularExpressionValidator)  in user controls.User controls are not posting back like the events are not wiring up.If I remove Validation controls in User controls page,user controls are working fine.Can anyone please help me out in getting it fixed. In the Validation controls, make sure you are setting the ControlToValidate property to the control that it links to.  If you're in .NET 2.0, it's also a good idea to put all the validation controls in the same Valid...

User Control controls not created when dynamically creating user control
  Have created a user control for displaying and editing a dynamically number of values. The user control contains two labels and an edit box. When dynamically loading the user control I get an error when the control itself tries to change setting on the fields within the user control.   Why doesnt this work? It works okay if I dont load it dynamically but create a user-control-instance in the aspx-page but thats no solution.   Thankyou!     Here is my code:   ucDataValue.ascx   <%@ Control Language="C#" AutoEventWireup="true&...

Web resources about - Custom DataGrid control in user control -

Want to preview our new DataGrid for Xamarin.Forms?
tl;dr Zumero.DataGrid is a Xamarin.Forms control for displaying data in rows and columns. If you would be interested in testing and previewing ...

Mad King DataGrid
This post is about scrolling in WPF and the egocentric DataGrid control. I’ll give the project background but if all you’re interested in is ...

Stack Overflow
Stack Exchange log in - careers - chat - meta - about - faq Questions Tags Users Badges Unanswered Ask Question Top Questions interesting 295 ...

Microsoft Silverlight - Wikipedia, the free encyclopedia
Microsoft Silverlight is an application framework for writing and running rich Internet applications , with features and purposes similar to ...

Flash Builder Plug-in for SAP Netweaver Gateway - Adobe Labs
Search Navigation Labs Home Wiki Home Technologies Alchemy Blueprint Camera Profiles and DNG Profile Editor Cirrus ColdFusion 10 DNG Codec Fireworks ...

Casaba Security » Products » X5s Testing Tool For Finding XSS Vulnerabilities
Security analysis, consulting, development and testing partners who understand your business strategy.

CodeGuru - Microsoft developers related ideas, articles, tips, tricks, comments, downloads, and so much ...
CodeGuru is where developers can come to share ideas, articles, questions, answers, tips, tricks, comments, downloads, and so much more related ...

Caliburn Micro: WPF, Silverlight, WP7 and WinRT/Metro made easy.
A small, yet powerful framework designed for WPF, Silverlight and WP7. It implements a variety of UI patterns for solving real-world problems. ...

Quick Answers - CodeProject
Questions - Free source code and tutorials for Software developers and Architects.; Updated: 11 Jul 2012 11636: first draft of license proliferation committee report
FYI,the first draft report of the OSI's License Proliferation Committee.To join the OSI's license proliferation discuss email list, send anemail ...

Resources last updated: 12/21/2015 2:20:52 AM