This is a migrated thread and some comments may be shown as answers.

Adding Validators to Columns in a Hierarchical Grid

3 Answers 114 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Shane Milton
Top achievements
Rank 2
Shane Milton asked on 12 Feb 2009, 03:14 PM
I have a hierarchical grid where AutoGenerateColumns is FALSE (i.e. I specify all columns) but most columns I would like to use the specialized Telerik columns (GridBoundColumn, GridDateTimeColumn, GridNumericColumn, etc.), not GridTemplateColumn, but I would like to add validators for these fields when in Insert/Edit modes (I use popup style inserts/edits).

The best thing I have found so far is based on this post. This gets rather interesting, and hacky, because the ItemCreated event handler is for the entire grid and not for the specific MasterTableViews within the hierarchical grid. Is there a better way to do this? I would like to add things such as date ranges, numerical ranges, and a required validator, among other things (pretty simple validations) for this specific problem, but this really should be much more flexible than that, even.

My primary observation is that there is no simple way to just hook up a validator to an edit field, and this is something that should be a relatively trivial thing without requiring templates. I think it would make sense to add a new collection to a Grid, GridValidators, where I could add as many validators as I wanted. Then give each grid column a property, ValidatorToUse and link it up to one of those validators in that collection. Or perhaps allow the use to have several validators assigned to a single column somehow. Something...

And if I'm wrong and this exists, my apologies. I've missed some very obvious things in the past. ;-)

Thanks!
-Shane

3 Answers, 1 is accepted

Sort by
0
Princy
Top achievements
Rank 2
answered on 13 Feb 2009, 07:21 AM
Hello Shane,

You can check for the name property of the OwnerTableView and then add the RequiredFieldValidator as shown below:
aspx:
 <telerik:RadGrid ID="RadGrid1" DataSourceID="SqlDataSource1" runat="server" AutoGenerateColumns="false" OnItemCreated="RadGrid1_ItemCreated" > 
          <MasterTableView EditMode="PopUp" Name="Master" DataSourceID="SqlDataSource1"
             <DetailTables  > 
             <telerik:GridTableView DataSourceID="SqlDataSource2" EditMode="PopUp" Name="Detail1" > 
             <Columns> 
              <telerik:GridBoundColumn DataField="ProductName" UniqueName="ProductName"
              </telerik:GridBoundColumn> 
             ..... 

cs:
protected void RadGrid1_ItemCreated(object sender, GridItemEventArgs e) 
    { 
        if (e.Item is GridEditableItem && e.Item.IsInEditMode && e.Item.OwnerTableView.Name == "Detail1"
        { 
            GridEditableItem editItem = (GridEditableItem)e.Item; 
            TextBox txtbx = (TextBox)editItem["ProductName"].Controls[0]; 
            txtbx.ID = "TextBox"
            RequiredFieldValidator validator = new RequiredFieldValidator(); 
            validator.ErrorMessage = "RequiredField"
            validator.ControlToValidate = "TextBox"
            editItem["ProductName"].Controls.Add(validator); 
        } 
     } 

Thanks
Princy.
0
Shane Milton
Top achievements
Rank 2
answered on 13 Feb 2009, 02:12 PM
Thanks, Princy...

However, I've not found a way to implement such a technique to be a 100% solution. I specifically have problems with GridDateTimeColumn fields. Performing this technique results in a javascript error and I've made attempts to attach the validator to other controls within the resulting RadDatePicker control without success. I've reproduced this in a very simple application. Please see the attached code to reproduce the javascript error when you click "Edit".

Do you know how I could add a validator to such a control?

Thanks!! :-)

ASPX:
    <asp:ScriptManager ID="ScriptManager1" runat="server"
    </asp:ScriptManager> 
    <div> 
        <telerik:RadGrid ID="RadGrid1" runat="server" DataSourceID="ObjectDataSource1" OnItemCreated="grid_ItemCreated" 
            AutoGenerateEditColumn="true" AutoGenerateColumns="false"
            <MasterTableView Name="ThisGrid" CommandItemDisplay="TopAndBottom" EditMode="PopUp"
                <Columns> 
                    <telerik:GridDateTimeColumn DataField="DateCreated" DataType="System.DateTime" HeaderText="Date Created" 
                        SortExpression="DateCreated" UniqueName="DateCreated"
                    </telerik:GridDateTimeColumn> 
                </Columns> 
            </MasterTableView> 
        </telerik:RadGrid> 
    </div> 
    <asp:ObjectDataSource ID="ObjectDataSource1" runat="server" InsertMethod="InsertFoo" 
        SelectMethod="GetFoo" TypeName="GridDateRequiredValidatorPoC.Foo" UpdateMethod="InsertFoo"
        <UpdateParameters> 
            <asp:Parameter Name="dateCreated" Type="DateTime" /> 
        </UpdateParameters> 
        <InsertParameters> 
            <asp:Parameter Name="dateCreated" Type="DateTime" /> 
        </InsertParameters> 
    </asp:ObjectDataSource> 
 

Code-Behind:
        protected void grid_ItemCreated( object sender, Telerik.Web.UI.GridItemEventArgs e ) 
        { 
            GridEditableItem item = e.Item as GridEditableItem; 
 
            // Only do this for items we're inserting/editing. 
            if ( item is GridEditableItem && item.IsInEditMode ) 
            { 
                switch ( item.OwnerTableView.Name.ToLower() ) 
                { 
                    case "thisgrid"
                        // EffectiveDate Column (Required) 
                        AddValidatorToEditField( item[ "DateCreated" ].Controls[ 0 ], "DateCreated" ); 
                        break
                    default
                        break
                } 
            } 
        } 
 
        private void AddValidatorToEditField( Control ctrlToValidate, string dataField ) 
        { 
            RequiredFieldValidator requiredValidator = new RequiredFieldValidator(); 
 
            if ( ( ctrlToValidate is RadDatePicker ) ) 
            { 
                // RadDatePickers already have an ID set so we can't set it. However, this still doesn't work. :-/ 
                requiredValidator.ControlToValidate = ( (RadDatePicker)ctrlToValidate ).ID; 
            } 
            else 
            { 
                // For some reason these controls were originally being rendered with no ID so ctrlToValidate.ID was an empty string. This fixed that. 
                ctrlToValidate.ID = dataField; 
                requiredValidator.ControlToValidate = ctrlToValidate.ID; 
            } 
 
            requiredValidator.ID = dataField + ".RequiredValidator"
            requiredValidator.ErrorMessage = " * Required"
            requiredValidator.EnableClientScript = true
            ctrlToValidate.Parent.Controls.Add( requiredValidator ); 
        } 

Data Object for the ObjectDataSource:
    // Goes nowhere, does nothing 
    public class Foo 
    { 
        public DateTime DateCreated { getset; } 
 
        [DataObjectMethod( DataObjectMethodType.Select )] 
        public List<Foo> GetFoo() 
        { 
            List<Foo> foos = new List<Foo>(); 
            Foo foo; 
 
            for ( int i = 0; i < 8; i++ ) 
            { 
                foo = new Foo(); 
                foo.DateCreated = DateTime.Now.Subtract( new TimeSpan( ( new Random() ).Next( 50000 ) ) ); 
                foos.Add( foo ); 
            } 
 
            return foos; 
        } 
 
        [DataObjectMethod( DataObjectMethodType.Insert )] 
        public void InsertFoo( DateTime dateCreated ) 
        { 
            // Code to make sure compiler doesn't do dumb things 
            if ( dateCreated < DateCreated ) 
            { 
                throw new Exception(); 
            } 
        } 
 
        [DataObjectMethod( DataObjectMethodType.Update )] 
        public void UpdateFoo( DateTime dateCreated ) 
        { 
            // Code to make sure compiler doesn't do dumb things 
            if ( dateCreated < DateCreated ) 
            { 
                throw new Exception(); 
            } 
        } 
    } 
 

0
Princy
Top achievements
Rank 2
answered on 16 Feb 2009, 01:47 PM
Hello Shane,

The javascript error you tried occurs as you have set the EnableClientScript for the RequiredFieldValidator to true. Try setting it to false to avoid the error. I tried your code, but couldnt get it to work as expected. You can try the following code instead:
cs:
protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e) 
    { 
        if (e.Item is GridEditableItem && e.Item.IsInEditMode) 
        { 
            GridEditableItem item = (GridEditableItem)e.Item; 
            switch (item.OwnerTableView.Name) 
            { 
                case "Detail2": 
                    // EffectiveDate Column (Required)  
                    AddValidatorToEditField(item, "date"); 
                    break; 
                default: 
                    break; 
            } 
        }  
   } 
 
private void AddValidatorToEditField(GridEditableItem editItem, string dataField) 
    { 
        RadDatePicker rddtpickr = (RadDatePicker)editItem["DateCreated"].Controls[0]; 
        rddtpickr.ID = dataField
        RequiredFieldValidator validator = new RequiredFieldValidator(); 
        validator.ErrorMessage = "* Required"
        validator.ControlToValidate = rddtpickr.ID
        editItem["DateCreated"].Controls.Add(validator); 
    } 

Thanks
Princy.
Tags
Grid
Asked by
Shane Milton
Top achievements
Rank 2
Answers by
Princy
Top achievements
Rank 2
Shane Milton
Top achievements
Rank 2
Share this question
or