[This post is part of the developer's manual preview published on this blog. You can find temporary TOC here.]
RadGrid dataGrid = base.Container.GetControl<RadGrid>("dataGrid", true); |
While, the approach we have demonstrated will work fine there are several problems we may run into:
- We have obtained the control in a private field. If we happen to need the reference to the RadGrid control, we’ll need to repeat this code throughout our View
- Being the private field, Views that derive from our View will not be able to access it and will need to repeat the logic for obtaining the reference to the control
- We have “hard-coded” the ID of the control to “dataGrid”. If we are to derive from this View and would implement a new template for the View, we would not be able to change the id of the grid in the template, but would be stuck with the “dataGrid”.
- We have made the dataGrid control required (by passing the “true” as a second argument). In our derived View, we may decide that we don’t need this grid. But since the control is required, removing the grid from the template would throw an exception.
So, we have seen that there are many problems associated with this approach. The better and more flexible approach would be to declare a virtual property which would hold the reference to a particular control. The code would look like this:
protected virtual RadGrid DataGrid |
{ |
get |
{ |
return base.Container.GetControl<RadGrid>("dataGrid", true); |
} |
} |
First of all, we don’t need to call the GetControl method every time we need to reference the grid. Instead, we can now simply call the property. So, let us suppose we’d like to enable the sorting on the grid in any given method; all we need to do is this:
this.DataGrid.AllowSorting = true; |
base.DataGrid.AllowSorting = false; |
protected override RadGrid DataGrid |
{ |
get |
{ |
return base.Container.GetControl<RadGrid>("financialGrid", true); |
} |
} |
Finally, we had the problem of having our DataGrid being a required control. Similarly to the problem of hard-coded id, we can again override the property and make the control optional.
protected override RadGrid DataGrid |
{ |
get |
{ |
return base.Container.GetControl<RadGrid>("financialGrid", false); |
} |
} |
if(this.DataGrid != null) |
this.DataGrid.AllowSorting = true; |