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

ObjectDataSource insert using Data Object Type and parameter values from session and querystring

10 Answers 724 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Erick
Top achievements
Rank 1
Erick asked on 07 Jul 2008, 09:47 PM
I am using the automatic inline edit/insert on a radgrid that is bound to an ObjectDataSource based on a business object.  Edits and deletes work great, but I am having problems getting the insert to work correctly.

Here are the columns in the radgrid:
<Columns> 
    <telerik:GridBoundColumn DataField="NoteID" DataType="System.Int32" HeaderText="NoteID" SortExpression="NoteID" UniqueName="NoteID" Visible="false" ReadOnly="true" /> 
    <telerik:GridDateTimeColumn DataField="NoteDate" DataType="System.DateTime" UniqueName="NoteDate" HeaderText="Date" HeaderStyle-Width="1" AllowSorting="true" DataFormatString="{0:M/d/yyyy}" />                                                 
    <telerik:GridBoundColumn DataField="Note" HeaderText="Note" SortExpression="Note" UniqueName="Note" /> 
    <telerik:GridBoundColumn DataField="UserID" DataType="System.Int32" HeaderText="UserID" SortExpression="UserID" UniqueName="UserID1" Visible="false" ReadOnly="true"   />            
    <telerik:GridBoundColumn DataField="StudentID" DataType="System.Int32" HeaderText="StudentID" SortExpression="StudentID" UniqueName="StudentID1" Visible="false" ReadOnly="true" />          
</Columns> 
 

Here is the ObjectDataSource:
<asp:ObjectDataSource ID="dsNotes" runat="server" DataObjectTypeName="StudentNote" TypeName="StudentNoteManager" DeleteMethod="Delete" InsertMethod="Save" SelectMethod="GetNotes" UpdateMethod="Save"
    <InsertParameters> 
        <asp:QueryStringParameter Name="StudentID" QueryStringField="sid" Type="Int32" /> 
        <asp:SessionParameter SessionField="UserID" Name="UserID" Type="Int32" /> 
    </InsertParameters> 
</asp:ObjectDataSource> 
 

When I do an insert, a new note is created, however, the 2 fields that should be set by the insert parameters are set to 0.

Am I missing something?

10 Answers, 1 is accepted

Sort by
0
Veli
Telerik team
answered on 08 Jul 2008, 02:32 PM
Hi Erick,

Could you please provide some sample code from RadGrid's relation to the data source.

Greetings,
Veli
the Telerik team

Instantly find answers to your questions at the new Telerik Support Center
0
Erick
Top achievements
Rank 1
answered on 08 Jul 2008, 02:44 PM
<telerik:RadGrid ID="StudentNoteList" AllowCustomPaging="True" AllowSorting="True"  AllowAutomaticUpdates="True" AllowAutomaticDeletes="True" AllowAutomaticInserts="True" DataSourceID="dsNotes" OnItemCommand="StudentNoteList_ItemCommand" AutoGenerateDeleteColumn="true" PageSize="5" AllowPaging="True" runat="server" GridLines="None"  > 
    <PagerStyle Mode="NextPrevAndNumeric"></PagerStyle> 
    <MasterTableView CommandItemDisplay="Top" CommandItemSettings-AddNewRecordText="New" CommandItemSettings-AddNewRecordImageUrl="~/images/icons/new.gif"  DataSourceID="dsNotes" DataKeyNames="NoteID,UserID,StudentID" AutoGenerateColumns="False"
 

Is that enough info?
0
Veli
Telerik team
answered on 09 Jul 2008, 09:01 AM
Hello Erick,

I couldn't identify any errors with the provided sample code. Could you please try manually inserting into the object data source control. You can do this in the InsertCommand event handler of RadGrid by invoking the Insert method of the data source control:

ObjectDataSource1.InsertParameters[“paremeterName”].DefaultValue = value;
ObjectDataSource1.Insert();
Please note that you need to set AllowAutomaticInserts to false in RadGrid's settings, as you are manually inserting your data.

Regards,
Veli
the Telerik team

Instantly find answers to your questions at the new Telerik Support Center
0
Erick
Top achievements
Rank 1
answered on 09 Jul 2008, 05:52 PM
I did the following:

1. I set AllowAutomaticInserts="False" on the rad grid.
2. I set OnInsertCommand="StudentNoteList_InsertCommand"
3. I added the following method:

protected void StudentNoteList_InsertCommand(object source, GridCommandEventArgs e) { 
  dsNotes.InsertParameters["UserID"].DefaultValue = "1"
  dsNotes.InsertParameters["StudentID"].DefaultValue = "2"
  dsNotes.Insert(); 

When I try this, I get the error:

ObjectDataSource dsNotes has no values to insert. Check that the 'values' dictionary contains values.
0
Veli
Telerik team
answered on 10 Jul 2008, 09:07 AM
Hi Erick,

How do you insert your other values to the data source? You may need to use the mentioned approach (setting InsertParameters by key) for all the data values to be inserted.

All the best,
Veli
the Telerik team

Instantly find answers to your questions at the new Telerik Support Center
0
Erick
Top achievements
Rank 1
answered on 10 Jul 2008, 03:07 PM
protected void StudentNoteList_InsertCommand(object source, GridCommandEventArgs e) {  
  dsNotes.InsertParameters["UserID"].DefaultValue = "1";  
  dsNotes.InsertParameters["StudentID"].DefaultValue = "2"
  dsNotes.InsertParameters.Add( "Note""this is a sample note" ); 
  dsNotes.InsertParameters.Add( "NoteDate", DateTime.Now.ToString( ) ); 
  dsNotes.InsertParameters.Add("NoteTypeID""1234"); 
  dsNotes.Insert();  
}  

I added the other parameters as well and still get the same error.

Based on other research, there appears to be some issue with ObjectDataSource inserts when the DataObjectTypeName is set and is pointing to a business object.  After some further playing, it seems that when we use AllowAutomaticInserts="True", it will create the business object specified by the DataObjectTypeName parameter, fill it with the correct data from the insert edit form and create a new record, but it will not correctly set the values for any InsertParameters.

Are you aware of any known issues with the ObjectDataSource that would cause what I am describing?
0
Veli
Telerik team
answered on 11 Jul 2008, 07:08 AM
Hello Erick,

Please find attached a sample project demonstrating RadGrid's insert functionality and ObjectDataSource. Please see how it applies to your case. If needed, you may try replacing your data source with the one provided in the sample to see if your RadGrid also works properly with it.

Greetings,
Veli
the Telerik team

Instantly find answers to your questions at the new Telerik Support Center
0
Chris Cottrell
Top achievements
Rank 1
answered on 11 Jul 2011, 07:07 PM
This looks like a fairly old issue, but looks like the same issue I have... 

here is my ObjectDataSource.. Note the use of DataObjectTypeName, which allows me to send the entity to my method and not individual parameters.

<asp:ObjectDataSource ID="odsProjects" runat="server"
        TypeName="Deloitte.MHP.Data.DAL"
        SelectMethod="GetProjects"
        InsertMethod="InsertProject"       
        DataObjectTypeName="Deloitte.MHP.Data.Project"  />

And here is my grid...

<telerik:radgrid ID="RadGrid1" runat="server"
        DataSourceID="odsProjects" AutoGenerateColumns="False" GridLines="None"
        AllowPaging="True" OnItemCommand="RadGrid1_ItemCommand"
        AllowAutomaticInserts="True"
        AllowAutomaticUpdates="True" >
        <ExportSettings IgnorePaging="true" OpenInNewWindow="true">
                <Pdf PageHeight="297mm" PageWidth="210mm" PageTitle="Your projects" />
            </ExportSettings>
        <MasterTableView CommandItemDisplay="Top" DataSourceID="odsProjects" DataKeyNames="ProjectID">
            <CommandItemSettings ExportToPdfText="Export to Pdf"></CommandItemSettings>
            <Columns>
                <telerik:GridHyperLinkColumn DataNavigateUrlFields="ProjectKey"
                    DataNavigateUrlFormatString="~/ComponentSelection.aspx?id={0}"
                    DataType="System.Int64" HeaderText="Action" Text="Select" UniqueName="column1">
                </telerik:GridHyperLinkColumn>
                <telerik:GridBoundColumn DataField="Name" HeaderText="Name" UniqueName="column">
                </telerik:GridBoundColumn>
            </Columns>
            <EditFormSettings UserControlName="NewProject.ascx" EditFormType="WebUserControl">
                <EditColumn UniqueName="EditCommandColumn">
                </EditColumn>
            </EditFormSettings>
        </MasterTableView>
        <ClientSettings>
                <ClientEvents OnRowDblClick="RowDblClick" />
            </ClientSettings>
        <HeaderContextMenu EnableImageSprites="True" CssClass="GridContextMenu GridContextMenu_Default"></HeaderContextMenu>
    </telerik:radgrid>


And then in my DAL, I have the following method..

public Guid InsertProject(Project entity)
        {
            entity.ProjectID = Guid.NewGuid();
            _context.Projects.AddObject(entity);
            _context.SaveChanges();
            return entity.ProjectID;
        }

I cannot separate the fields out. i would rather pass the object itself to the method instead of all the fields. It seems like you're unable to pass the value back. Also, I am using a user control for inserts (not doing updates). I tried it using the the the type of Project for the DataItem instead of object, but that doesn't work either. 

public partial class NewProject : System.Web.UI.UserControl
    {
        private Project _dataItem = null;
 
        public Project DataItem
        {
            get
            {
                return this._dataItem;
            }
            set
            {
                this._dataItem = value;
            }
        }
 
        protected void Page_Load(object sender, EventArgs e)
        {
 
        }
 
        protected void odsProjects_Inserted(object sender, ObjectDataSourceStatusEventArgs e)
        {
            Response.Redirect(string.Format("~/ComponentSelection.aspx?id={0}", (Guid)e.ReturnValue));
        }
    }

Any ideas for this besides needing to write my DAL differently (and in my opinion, the wrong way)?
0
Chris Cottrell
Top achievements
Rank 1
answered on 11 Jul 2011, 07:58 PM
OK.. It does seem to work if you put your insert control in a template. Any big difference between the two? They seem to do the same thing. 

<telerik:radgrid ID="RadGrid1" runat="server"
        DataSourceID="odsProjects" AutoGenerateColumns="False" GridLines="None"
        AllowPaging="True" OnItemCommand="RadGrid1_ItemCommand" OnInsertCommand="RadGrid1_InsertCommand"
        AllowAutomaticInserts="true"
        AllowAutomaticUpdates="True" >
        <ExportSettings IgnorePaging="true" OpenInNewWindow="true">
                <Pdf PageHeight="297mm" PageWidth="210mm" PageTitle="Your projects" />
            </ExportSettings>
        <MasterTableView CommandItemDisplay="Top" DataSourceID="odsProjects" DataKeyNames="ProjectID">
            <CommandItemSettings ExportToPdfText="Export to Pdf"></CommandItemSettings>
            <Columns>
                <telerik:GridHyperLinkColumn DataNavigateUrlFields="ProjectKey"
                    DataNavigateUrlFormatString="~/ComponentSelection.aspx?id={0}"
                    DataType="System.Int64" HeaderText="Action" Text="Select" UniqueName="column1">
                </telerik:GridHyperLinkColumn>
                <telerik:GridBoundColumn DataField="Name" HeaderText="Name" UniqueName="column">
                </telerik:GridBoundColumn>
            </Columns>
            <EditFormSettings EditFormType="Template">
                <FormTemplate>
                    <fieldset>
                        <legend>Project Details</legend>
                        <ol>
                        <li>
                            <label for="txtProjectName">Project Name: <span style="color: Red">*</span> </label>
                            <telerik:RadTextBox id="txtProjectName" Runat="server"
                                EmptyMessage="Enter project name:"
                                Text='<%# Bind("Name") %>' Columns="45" />
                            <asp:RequiredFieldValidator ID="TextBoxRequiredFieldValidator" runat="server" Display="Dynamic"
                                ControlToValidate="txtProjectName" ErrorMessage="The textbox can not be empty!" />
                        </li>
                        <li>
                            <label for="txtChargeCode">Enter charge code used in charging time:</label>
                            <telerik:RadTextBox id="txtChargeCode" Runat="server"
                                EmptyMessage="Enter dtrak charge code:"
                                Text='<%# Bind("ChargeCode") %>' Columns="40" />
                        </li>
                        <li>
                            <asp:Checkbox ID="ckbOnboarded" runat="server"
                                Checked='<%# Bind("Onboarded") %>'
                                Text="Onboarded?" />
                        </li>                   
                        <li>
                            <telerik:RadButton runat="server" id="btnInsert"
                                Text="Save And Continue" CommandName="PerformInsert" />
                            <asp:Button ID="btnCancel" Text="Cancel" runat="server" CausesValidation="False"
                                CommandName="Cancel"></asp:Button>
                        </li>
                        </ol>
                    </fieldset>
                </FormTemplate>
            </EditFormSettings>
        </MasterTableView>
        <ClientSettings>
                <ClientEvents OnRowDblClick="RowDblClick" />
            </ClientSettings>
        <HeaderContextMenu EnableImageSprites="True" CssClass="GridContextMenu GridContextMenu_Default"></HeaderContextMenu>
    </telerik:radgrid>
0
Veli
Telerik team
answered on 12 Jul 2011, 12:09 PM
Hello Chris,

There is no difference in terms of data CRUD operations between the FormTemplate editing and the WebUserControl editing. In any case, RadGrid tries to extract the edited values and pass them to the DataSourceView returned from the ObjectDataSource (or any other DataSource control). In this respect, the difference in your case can come from the way data values are extracted from the edit form. Note that when using WebUserControl editing, your web user control does not, by default, support automatic data extraction. To make it extraction-ready, you need to implement the IBindableControl interface in your user control class. This interface defines a single method - ExtractValues. It is used by RadGrid for extracting your edited values. If you want to keep using the user control for data editing and also use automatic data source operations in RadGrid, you need to implement this method properly. The method populates an IDictionary object of name-value pairs containing your modified data, field by field. Note here no reference to the custom data entity object is made. Conversion from a dictionary of edited values to an actual data object instance is done automatically by the ObjectDataSource.

Greetings,
Veli
the Telerik team

Register for the Q2 2011 What's New Webinar Week. Mark your calendar for the week starting July 18th and book your seat for a walk through of all the exciting stuff we will ship with the new release!

Tags
Grid
Asked by
Erick
Top achievements
Rank 1
Answers by
Veli
Telerik team
Erick
Top achievements
Rank 1
Chris Cottrell
Top achievements
Rank 1
Share this question
or