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

GridCommandEventArgs.Item is null in InsertCommand

7 Answers 497 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Boyan
Top achievements
Rank 1
Boyan asked on 05 Oct 2011, 12:58 AM
Hi, I am trying to follow your example in the Telerik help pages (http://www.telerik.com/help/aspnet-ajax/grid-inserting-values-inplace-and-editforms.html) to implement inserting a new row into a RadGrid. I am using a button to fire InitInsert which successfully creates an empty row that the user can input information, but when I fire the InsertCommand by clicking another button, in the InsertCommand event handler, GridCommandEventArgs.Item evaluates to null. Any suggestions?

<telerik:RadScriptManager ID="RadScriptManager1" runat="server" />
                                <telerik:RadAjaxManager ID="RadAjaxManager1" runat="server">
                                    <AjaxSettings>
                                        <telerik:AjaxSetting AjaxControlID="grdTradesFile">
                                            <UpdatedControls>
                                                <telerik:AjaxUpdatedControl ControlID="grdTradesFile" LoadingPanelID="RadAjaxLoadingPanel1"/>
                                            </UpdatedControls>
                                        </telerik:AjaxSetting>
                                    </AjaxSettings>
                                </telerik:RadAjaxManager>
 
                                <telerik:RadAjaxLoadingPanel ID="RadAjaxLoadingPanel1" runat="server" Height="75px" Width="75px" Transparency="50" />
                                 
                                <telerik:RadGrid ID="grdTradesFile" runat="server" Skin="Web20" Width="97%"
                                    AllowMultiRowSelection="True" AllowMultiRowEdit="True"
                                    AllowAutomaticDeletes="True" AllowAutomaticInserts="True"
                                    AutoGenerateColumns="False" ShowStatusBar="true"
                                    OnNeedDataSource="grdTradesFile_NeedDataSource"
                                    SelectedItemStyle-BorderColor="Moccasin" SelectedItemStyle-BackColor="Moccasin"
                                    
                                    onitemcommand="grdTradesFile_ItemCommand"
                                    oncancelcommand="grdTradesFile_CancelCommand"
                                    oneditcommand="grdTradesFile_EditCommand"
                                    onupdatecommand="grdTradesFile_UpdateCommand"
                                    oninsertcommand="grdTradesFile_InsertCommand">
 
                                    <ClientSettings>
                                        <Selecting AllowRowSelect="true" />
                                    </ClientSettings>
 
                                    <MasterTableView CommandItemDisplay="Top" EditMode="InPlace" AllowAutomaticDeletes="false"
                                        AllowAutomaticInserts="true" AllowAutomaticUpdates="false" AutoGenerateColumns="false"
                                        Width="100%" DataKeyNames="Trade" ClientDataKeyNames="Trade">
                                        <CommandItemTemplate>
                                            <asp:Button ID="Button1" runat="server" CommandName="EditSelected" Text="Edit Selected" Width="120"
                                                Visible='<%# grdTradesFile.EditIndexes.Count == 0 %>'></asp:Button>
                                            <asp:Button ID="Button2" runat="server" CommandName="CancelAll" Text="Cancel All" Width="120"
                                                Visible='<%# grdTradesFile.EditIndexes.Count != 0 %>'></asp:Button>
                                            <asp:Button ID="Button3" runat="server" CommandName="UpdateEdited"  Text="Update Edited" Width="120"
                                                Visible='<%# grdTradesFile.EditIndexes.Count > 0 %>'></asp:Button>
                                            <asp:Button ID="Button4" runat="server" CommandName="DeleteSelected" Text="Delete Selected" Width="120"
                                                Visible='<%# grdTradesFile.EditIndexes.Count == 0 %>'></asp:Button>
                                            <asp:Button ID="Button5" runat="server" CommandName="InitInsert" Text="New Trade" Width="120"
                                                Visible='<%# !grdTradesFile.MasterTableView.IsItemInserted && grdTradesFile.EditIndexes.Count == 0 %>'></asp:Button>
                                            <asp:Button ID="Button6" runat="server" CommandName="PerformInsert" Text="Add Trade" Width="120"
                                                Visible='<%# grdTradesFile.MasterTableView.IsItemInserted %>'></asp:Button>
                                        </CommandItemTemplate>
                                        <Columns>
                                          <telerik:GridClientSelectColumn  />
                                          <telerik:GridBoundColumn DataField="Trade" HeaderText="TRADE" UniqueName="Trade"  />
                                          <telerik:GridBoundColumn DataField="Coupon" HeaderText="COUPON" UniqueName="Coupon" />
                                          <telerik:GridBoundColumn DataField="Price" HeaderText="PRICE" UniqueName="Price" />
                                          <telerik:GridBoundColumn DataField="Cross" HeaderText="PREMIUM CROSS" UniqueName="PremiumCross" />
                                          <telerik:GridBoundColumn DataField="Comments" HeaderText="COMMENTS" UniqueName="Comments" />
                                        </Columns>
                                 </MasterTableView>
                                </telerik:RadGrid>

protected void grdTradesFile_InsertCommand(object sender, GridCommandEventArgs e)
        {
            GridEditableItem editedItem = e.Item as GridEditableItem;
            DataRow newRow = tradesTable.NewRow();
 
            DataRow[] allValues = tradesTable.Select("", PRIMARY_KEY_COLUMN_NAME, DataViewRowState.CurrentRows);
            if (allValues.Length > 0)
            {
                newRow[PRIMARY_KEY_COLUMN_NAME] = (int)allValues[allValues.Length - 1][PRIMARY_KEY_COLUMN_NAME] + 1;
            }
            else
            {
                newRow[PRIMARY_KEY_COLUMN_NAME] = 1; //the table is empty;
            }
 
            //Set new values
            Hashtable newValues = new Hashtable();
            //The GridTableView will fill the values from all editable columns in the hash
            e.Item.OwnerTableView.ExtractValuesFromItem(newValues, editedItem);
 
            try
            {
                foreach (DictionaryEntry entry in newValues)
                {
                    newRow[(string)entry.Key] = entry.Value;
                }
            }
            catch (Exception ex)
            {
                
            }
 
            tradesTable.Rows.Add(newRow);
            grdTradesFile.Rebind();
            saveChanges();           
        }

7 Answers, 1 is accepted

Sort by
0
Boyan
Top achievements
Rank 1
answered on 06 Oct 2011, 04:41 PM
Just to give some more clarification: Upon InitInsert, an empty editable row appears in the grid, but after firing the PerformInsert command, the Item in GridCommandEventsArgs is null, so I am not able to access the editable item in order to retrieve the client input data and add the row to the DataSource.

Any suggestions why that could be? I seem to be following the example code almost verbatim.
0
Accepted
Marin
Telerik team
answered on 07 Oct 2011, 09:40 AM
Hi Boyan,

 I checked your code and on my side e.Item was evaluated to the parent item holding the button that fired the command. In the standard case this will suffice because normally a button that fires the "PerformInsert" command is placed inside the editable item that is about to be inserted and e.Item can be cast to GridEditableItem. However in your case the "Add Trade" button is in the CommandItemTemplate so e.Item evaluates to GridCommandItem which cannot be cast to GridEditableItem and the logic fails. To solve this you should manually obtain a reference to the desired insert item by calling the GetInsertItem method of the MasterTableView. Here is how the InsertCommand should look like in your case:

protected void grdTradesFile_InsertCommand(object sender, GridCommandEventArgs e)
    {
        GridEditableItem editedItem = grdTradesFile.MasterTableView.GetInsertItem();
 
        ////Set new values
        Hashtable newValues = new Hashtable();
        //The GridTableView will fill the values from all editable columns in the hash
        grdTradesFile.MasterTableView.ExtractValuesFromItem(newValues, editedItem);
         
        //save the values to the database
        
    }

You can check the correct behavior in the attached page. Best wishes,
Marin
the Telerik team
If you want to get updates on new releases, tips and tricks and sneak peeks at our product labs directly from the developers working on the RadControls for ASP.NET AJAX, subscribe to their blog feed now
0
Boyan
Top achievements
Rank 1
answered on 07 Oct 2011, 10:08 PM
Thanks Marin,

In this case, is there a way for me to access the edited item that gets created upon InitInsert. I'd like to define some default values for some of the columns of the new row? 

I appreciate your help.
0
Marin
Telerik team
answered on 11 Oct 2011, 09:35 AM
Hello Boyan,

 You can set default value for a column by setting its DefaultInsertValue property:

<telerik:GridBoundColumn DataField="Trade" DefaultInsertValue="default value" HeaderText="TRADE" UniqueName="Trade" />

or you can also do this in code behind in the ItemDataBound event:

protected void grdTradesFile_ItemDataBound(object sender, GridItemEventArgs e)
    {
        //e.Item is GridDataInsertItem in case of InPlace edit mode
        if (e.Item is GridDataInsertItem && (e.Item as GridDataInsertItem).IsInEditMode)
        {
            //in case the first control is textbox
            ((e.Item as GridDataInsertItem)["Trade"].Controls[0] as TextBox).Text = "default value";
        }
    }

Greetings,
Marin
the Telerik team
If you want to get updates on new releases, tips and tricks and sneak peeks at our product labs directly from the developers working on the RadControls for ASP.NET AJAX, subscribe to their blog feed now
0
Boyan
Top achievements
Rank 1
answered on 12 Oct 2011, 10:42 PM
Thanks for the suggestion, but I would actually be more interested in being able to dynamically set that value depending on different factors (e.g. set the primary key column value to +1 the max primary key currently in the table or inserting today's date in DateTime columns), so I do not think setting the DefaultInsertValue property would not work for me. As far as I have seen I can't set DefaultInsertValue to an expression that will evaluate in runtime since Telerik.Web.UI.GridBoundColumn does not have a DataBinding event.

I am wondering if it is at all possible to access that newly inserted row just like you would normally access a row in Edit mode and insert default values programmatically.

Thanks for the help!
0
Shinu
Top achievements
Rank 2
answered on 13 Oct 2011, 07:18 AM
Hello Boyan,

You can access the last inserted value in the ItemDataBound and can set the desired value as shows below.
Here is a sample code.
C#:
public partial class RadGrid_LastInserted : System.Web.UI.Page
{
    public SqlConnection SqlConnection = new SqlConnection(WebConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString);
    public SqlDataAdapter SqlDataAdapter = new SqlDataAdapter();
    DataTable dt=new DataTable();
    SqlCommand cmd;
protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
    {
        if (e.Item is GridEditFormItem && e.Item.IsInEditMode && e.Item.OwnerTableView.IsItemInserted)//checking for insert mode.
        {
            GridEditFormInsertItem insertItem = (GridEditFormInsertItem)e.Item;
            SqlConnection.Open();
            string LastRow="select max(ID)+1 from MyTable";//accessing the ID
            cmd = new SqlCommand(LastRow, SqlConnection);
            string id = cmd.ExecuteScalar().ToString();
            (insertItem["Id"].Controls[0] as TextBox).Text = id;//settingdefault value
        }
    }
}

Thanks,
Shinu.
0
Boyan
Top achievements
Rank 1
answered on 13 Oct 2011, 11:05 PM
Thanks, Shinu.

Just FYI, I had to modify the code snippet a bit in order to get it to work. e.Item evaluated as GridDataInsertItem in the ItemDataBound event handler, and I had to use GridEditableItem instead of GridEditFormItem in the if statement.
Tags
Grid
Asked by
Boyan
Top achievements
Rank 1
Answers by
Boyan
Top achievements
Rank 1
Marin
Telerik team
Shinu
Top achievements
Rank 2
Share this question
or