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

Inserting: KeyValues is empty

8 Answers 209 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Colin
Top achievements
Rank 1
Colin asked on 07 Mar 2012, 05:44 PM
Hi and thank you for reading.

When I attempt an insert with the following, it enters the function correctly, but the KeyValues property is always empty and, thus, it never enters the loop over the dictionary from ExtractValuesFromItem. As a result, it inserted a new blank row.
It also may be relevant to mention that this page has two RadGrid instances, including this one, but they're operating on separate data sources with separate scripting. The other RadGrid works fine with similar code, however I'm not allowing inserts on that one.
I would appreciate any advice or suggestions.

ASP.Net:
<telerik:RadScriptBlock runat="server" ID="nono">
            <telerik:RadGrid runat="server" ID="gridBids" OnNeedDataSource="gridBids_NeedDataSource" OnItemDataBound="gridBids_DataBound" OnUpdateCommand="gridBids_Update"
                OnInsertCommand="gridBids_Insert" OnDeleteCommand="gridBids_Delete" AutoGenerateColumns="false" Skin="Office2007" EnableAJAXLoadingTemplate="true" EnableAJAX="true"
                LoadingTemplateTransparency="25" ValidationSettings-CommandsToValidate="update,insert" ValidationSettings-ValidationGroup="gridBids">
                <MasterTableView EditMode="InPlace" CommandItemDisplay="Top" AllowAutomaticDeletes="false" AllowAutomaticInserts="false" AllowAutomaticUpdates="false" DataKeyNames="blockbidsegmentid">
                    <CommandItemSettings ShowExportToExcelButton="true" ShowAddNewRecordButton="true" />
                    <Columns>
                        <telerik:GridEditCommandColumn />
                        <telerik:GridTemplateColumn HeaderText="Carrier" UniqueName="bidCarrier">
                            <ItemTemplate><%# Eval("carrier") %></ItemTemplate>
                            <EditItemTemplate>
                                <telerik:RadTextBox runat="server" ID="txtBidCarrier" MaxLength="2" Width="40px" Text='<%# Eval("carrier") %>' />
                            </EditItemTemplate>
                            <InsertItemTemplate>
                                <telerik:RadTextBox runat="server" ID="txtBidCarrier" MaxLength="2" Width="40px" />
                            </InsertItemTemplate>
                        </telerik:GridTemplateColumn>
                        <telerik:GridTemplateColumn HeaderText="Flight#" UniqueName="bidFlightNum">
                            <ItemTemplate><%# Eval("flightnum") %></ItemTemplate>
                            <EditItemTemplate>
                                <telerik:RadTextBox runat="server" ID="txtBidFlightNum" MaxLength="4" Width="75px" Text='<%# Eval("flightnum") %>' />
                            </EditItemTemplate>
                            <InsertItemTemplate>
                                <telerik:RadTextBox runat="server" ID="txtBidFlightNum" MaxLength="4" Width="75px" />
                            </InsertItemTemplate>
                        </telerik:GridTemplateColumn>
                        <telerik:GridTemplateColumn HeaderText="From" UniqueName="bidFrom">
                            <ItemTemplate><%# Eval("fromairportcode") %></ItemTemplate>
                            <EditItemTemplate>
                                <telerik:RadTextBox runat="server" ID="txtBidFrom" Width="60px" MaxLength="3" Text='<%# Eval("fromairportcode") %>' />
                            </EditItemTemplate>
                            <InsertItemTemplate>
                                <telerik:RadTextBox runat="server" ID="txtBidFrom" Width="60px" MaxLength="3" />
                            </InsertItemTemplate>
                        </telerik:GridTemplateColumn>
                        <telerik:GridTemplateColumn HeaderText="To" UniqueName="bidTo">
                            <ItemTemplate><%# Eval("toairportcode") %></ItemTemplate>
                            <EditItemTemplate>
                                <telerik:RadTextBox runat="server" ID="txtBidTo" Width="60px" MaxLength="3" Text='<%# Eval("toairportcode") %>' />
                            </EditItemTemplate>
                            <InsertItemTemplate>
                                <telerik:RadTextBox runat="server" ID="txtBidTo" Width="60px" MaxLength="3" />
                            </InsertItemTemplate>
                        </telerik:GridTemplateColumn>
                        <telerik:GridTemplateColumn HeaderText="COS" UniqueName="bidCOS">
                            <ItemTemplate><%# Eval("cos") %></ItemTemplate>
                            <EditItemTemplate>
                                <telerik:RadTextBox runat="server" ID="txtBidCOS" Width="40px" MaxLength="1" Text='<%# Eval("cos") %>' />
                            </EditItemTemplate>
                            <InsertItemTemplate>
                                <telerik:RadTextBox runat="server" ID="txtBidCOS" Width="40px" MaxLength="1" />
                            </InsertItemTemplate>
                        </telerik:GridTemplateColumn>
                        <telerik:GridTemplateColumn HeaderText="Depart Time" UniqueName="bidDepartTime">
                            <ItemTemplate><%# (Eval("departtime").ToString().Length > 0) ? DateTime.Parse(Eval("departtime").ToString()).ToString("ddMMMyy HH:mm") : "" %></ItemTemplate>
                            <EditItemTemplate>
                                <telerik:RadDatePicker runat="server" ID="txtBidDepartDate" Width="90px" DateInput-DateFormat="ddMMMyy"
                                    SelectedDate='<%# (Eval("departtime").ToString().Length > 0) ? DateTime.Parse(Eval("departtime").ToString()) : DateTime.Now %>' />
                                <telerik:RadMaskedTextBox runat="server" ID="txtBidDepartTime" Width="45px" Mask="##:##" Style="text-align:center;"
                                    Text='<%# (Eval("departtime").ToString().Length > 0) ? DateTime.Parse(Eval("departtime").ToString()).ToString("HH:mm") : "" %>' />
                            </EditItemTemplate>
                            <InsertItemTemplate>
                                <telerik:RadDatePicker runat="server" ID="txtBidDepartDate" Width="90px" DateInput-DateFormat="ddMMMyy" />
                                <telerik:RadMaskedTextBox runat="server" ID="txtBidDepartTime" Width="45px" Mask="##:##" Style="text-align:center;" />
                            </InsertItemTemplate>
                        </telerik:GridTemplateColumn>
                        <telerik:GridTemplateColumn HeaderText="Arrive Time" UniqueName="bidArriveTime">
                            <ItemTemplate><%# (Eval("arrivetime").ToString().Length > 0) ? DateTime.Parse(Eval("arrivetime").ToString()).ToString("ddMMMyy HH:mm") : "" %></ItemTemplate>
                            <EditItemTemplate>
                                <telerik:RadDatePicker runat="server" ID="txtBidArriveDate" Width="90px" DateInput-DateFormat="ddMMMyy"
                                    SelectedDate='<%# (Eval("arrivetime").ToString().Length > 0) ? DateTime.Parse(Eval("arrivetime").ToString()) : DateTime.Now %>' />
                                <telerik:RadMaskedTextBox runat="server" ID="txtBidArriveTime" Width="45px" Mask="##:##" Style="text-align:center;"
                                    Text='<%# (Eval("arrivetime").ToString().Length > 0) ? DateTime.Parse(Eval("arrivetime").ToString()).ToString("HH:mm") : "" %>' />
                            </EditItemTemplate>
                            <InsertItemTemplate>
                                <telerik:RadDatePicker runat="server" ID="txtBidArriveDate" Width="90px" DateInput-DateFormat="ddMMMyy" />
                                <telerik:RadMaskedTextBox runat="server" ID="txtBidArriveTime" Width="45px" Mask="##:##" Style="text-align:center;" />
                            </InsertItemTemplate>
                        </telerik:GridTemplateColumn>
                        <telerik:GridTemplateColumn HeaderText="Base Fare" UniqueName="bidBaseFare">
                            <ItemTemplate><%# String.Format("{0:C}", Eval("basefare")) %></ItemTemplate>
                            <EditItemTemplate>
                                <telerik:RadNumericTextBox runat="server" ID="txtBidBaseFare" Type="Currency" Width="90px" Style="text-align:right;"
                                    Value='<%# (Eval("basefare").ToString().Length > 0) ? Decimal.Parse(Eval("basefare").ToString()) : Decimal.Parse("0.00") %>' />
                            </EditItemTemplate>
                            <InsertItemTemplate>
                                <telerik:RadNumericTextBox runat="server" ID="txtBidBaseFare" Type="Currency" Width="90px" Style="text-align:right;" />
                            </InsertItemTemplate>
                        </telerik:GridTemplateColumn>
                        <telerik:GridTemplateColumn HeaderText="Notes" UniqueName="bidNotes">
                            <ItemTemplate>
                                <input type="button" name="btnShowBidNotes" value="Show All Notes" onClick="showAllNotes('<%# FormatNotes(Eval("notes"),true) %>');" />
                                <%# FormatNotes(Eval("notes"),false) %>
                            </ItemTemplate>
                            <EditItemTemplate>
                                <telerik:RadTextBox runat="server" ID="txtBidNotes" Rows="5" Columns="60" TextMode="MultiLine" Font-Size="Smaller" />
                            </EditItemTemplate>
                            <InsertItemTemplate>
                                <telerik:RadTextBox runat="server" ID="txtBidNotes" Rows="5" Columns="60" TextMode="MultiLine" Font-Size="Smaller" />
                            </InsertItemTemplate>
                        </telerik:GridTemplateColumn>
                    </Columns>
                </MasterTableView>
            </telerik:RadGrid>
            </telerik:RadScriptBlock>

C#:
protected void gridBids_NeedDataSource(object sender, EventArgs ev)
    {
        this.gridBids.DataSource = this.bidsTable;
    }
 
    protected void gridBids_DataBound(object source, Telerik.Web.UI.GridItemEventArgs ev)
    {
         
    }
 
    protected void gridBids_Command(object source, Telerik.Web.UI.GridCommandEventArgs ev)
    {
 
    }
 
    protected void gridBids_Insert(object sender, GridCommandEventArgs ev)
    {
        if (!(ev.Item is GridEditableItem) || !ev.Item.IsInEditMode) return;
 
        DataRow row = this.bidsTable.NewRow();
        GridEditableItem insertedItem = ev.Item.OwnerTableView.GetInsertItem();
 
        if (this.m_editing) row["blockbidsegmentid"] = 0;
        else
        {
            DataRow[] currentRows = this.bidsTable.Select("", "blockbidsegmentid");
 
            if (currentRows.Length > 0) row["blockbidsegmentid"] = ((int)currentRows[currentRows.Length - 1]["blockbidsegmentid"]) + 1;
            else row["blockbidsegmentid"] = 0;
        }
 
        Hashtable newValues = new Hashtable();
        insertedItem.OwnerTableView.ExtractValuesFromItem(newValues, insertedItem);
 
        try
        {
            foreach (DictionaryEntry entry in newValues)
            {
                object val = entry.Value;
                string key = (string)entry.Key;
 
                string dbField = this.bidCols[Array.IndexOf(this.bidGridCols, key)];
                if (dbField.Length == 0) continue;
 
                if (key == "bidCarrier" || key == "bidFrom" || key == "bidTo" || key == "bidCOS") val = val.ToString().ToUpper();
                else if (key == "bidDepartTime")
                {
                    TimeSpan departts = new TimeSpan(Int32.Parse((((RadMaskedTextBox)insertedItem["bidDepartTime"].FindControl("txtBidDepartTime")).Text).Substring(0, 2)), Int32.Parse((((RadMaskedTextBox)insertedItem["bidDepartTime"].FindControl("txtBidDepartTime")).Text).Substring(3)), 0);
                    val = ((DateTime)((RadDatePicker)insertedItem["bidDepartTime"].FindControl("txtBidDepartDate")).SelectedDate).Date + departts;
                }
                else if (key == "bidArriveTime")
                {
                    TimeSpan arrivets = new TimeSpan(Int32.Parse((((RadMaskedTextBox)insertedItem["bidArriveTime"].FindControl("txtBidArriveTime")).Text).Substring(0, 2)), Int32.Parse((((RadMaskedTextBox)insertedItem["bidArriveTime"].FindControl("txtBidArriveTime")).Text).Substring(3)), 0);
                    val = ((DateTime)((RadDatePicker)insertedItem["bidArriveTime"].FindControl("txtBidArriveDate")).SelectedDate).Date + arrivets;
                }
 
                row[dbField] = val;
            }
 
            this.bidsTable.Rows.Add(row);
 
            this.gridBids.Rebind();
        }
        catch (Exception ex)
        {
            gridBids.Controls.Add(new LiteralControl("Unable to insert record. Reason: " + ex.Message));
            ev.Canceled = true;
        }
    }

Thank you in advance.

8 Answers, 1 is accepted

Sort by
0
Princy
Top achievements
Rank 2
answered on 08 Mar 2012, 09:17 AM
Hello Colin,

ExtractValuesFromItem(dictonaryObject, editedItem) method create an empty dictionary object and pass it as first parameter of the ExtractValuesFromItem() method to extract the values from the inserted item (which is the second parameter to that method). The dictionary object will hold key -> value pairs where each key will be the DataField of the insertion field column and the corresponding value will be the data entered by the user. So can add one column to grid for DataKey field value like below.

ASPX:

<telerik:GridBoundColumn HeaderText="blockbidsegmentid" DataField="blockbidsegmentid" ReadOnly="True"
        UniqueName="blockbidsegmentid" Display="False">

Please refer this document for information.

Inserting Values Using InPlace and EditForms Modes

Hope this helps,
Princy.
0
Colin
Top achievements
Rank 1
answered on 08 Mar 2012, 02:26 PM
Hi, and thank you for your reply.
I added the following line to my code as you suggested:
<telerik:GridBoundColumn UniqueName="blockbidsegmentid" DataField="blockbidsegmentid" Display="false" ReadOnly="true" />

However, the problem still persists. It inserts a blank row.
I would appreciate if you had any other suggestions.

It may also be helpful for you if I include the following declaration of the DataTable being used as the datasource of the grid:

private string[] bidCols = { "carrier", "flightnum", "fromairportcode", "toairportcode", "cos", "departtime", "arrivetime", "basefare", "status", "notes", "historicalid", "insertdate" };
 
protected DataTable bidsTable
{
    get
    {
        if (this.ViewState["bidsTable"] == null)
        {
            DataTable tbl = new DataTable();
            tbl.TableName = "bids";
            DataColumn dc = new DataColumn("blockbidsegmentid", Type.GetType("System.Int32"));
            tbl.Columns.Add(dc);
            tbl.PrimaryKey = new DataColumn[] { tbl.Columns[0] };
            foreach (string col in bidCols)
            {
                Type type;
                if (col == "basefare") type = Type.GetType("System.Decimal");
                else if (col == "status") type = Type.GetType("System.Int32");
                else if (col == "departtime" || col == "arrivetime") type = Type.GetType("System.DateTime");
                else type = Type.GetType("System.String");
                dc = new DataColumn(col, type);
                tbl.Columns.Add(col);
            }
 
            this.ViewState["bidsTable"] = tbl;
        }
        return (DataTable)this.ViewState["bidsTable"];
    }
    set
    {
        this.ViewState["bidsTable"] = value;
    }
}
0
Colin
Top achievements
Rank 1
answered on 09 Mar 2012, 08:56 PM
So I guess there are no further ideas on this one?

Maybe a clue for you:
Updating started breaking as well, but only for RadTextBox controls. It would always return the old values. The RadNumericTextBox and RadMaskTextBox and RadDatePicker controls all worked and updated fine. After spending a day on this, I solved it by changing my RadTextBox controls to regular asp:TextBox controls. I was using the following to access them:

((RadTextBox)editedItem.FindControl("txtMyControlID")).Text

This returned the old value.
Once I changed this to a regular TextBox though, it started returning the new value.

My theory is that there are at least two controls being created with RadTextBox and that the actual ID of the control from the ASP.Net page was not the control that I was supposed to be accessing.

I have a strong feeling that my insert operation failing is due to the exact same problem, as all the default values in the insert templates are blank.
Am I on to something here? I would much rather use the RadTextBox controls, but if they don't work, I don't really see why I would.
0
Tsvetina
Telerik team
answered on 12 Mar 2012, 10:30 AM
Hello Colin,

On insert, the key values are expected to be empty, as the RadGrid control does not create them - either you manually insert them to the new record or if the field is an identity one, it is auto-generated by the db. So, on insert it is expected to get an empty key value. Can you confirm that all other values in the dictionary are empty, too?

As for update, there should be no problem using a RadTextBox, can you also paste your UpdateCommand code, so we can look for any possible mistakes?

Regards,
Tsvetina
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
Colin
Top achievements
Rank 1
answered on 12 Mar 2012, 03:55 PM
Well, I must say that's a little funny because your Example 1 on the RadGrid insert documentation page (http://www.telerik.com/help/aspnet-ajax/grid-inserting-values-inplace-and-editforms.html) shows this method being used.
I have replaced it with a script that uses FindControl and have gotten it to work.

The update script is as follows. As I said, all but the RadTextBox controls - except for txtBidNotes, which has no initial value - work. I have replaced the RadTextBox controls with TextBox controls and it works fine.

protected void gridBids_Update(object sender, GridCommandEventArgs ev)
{
    if (!(ev.Item is GridEditableItem) || !ev.Item.IsInEditMode) return;
 
    GridEditableItem editedItem = (GridEditableItem)ev.Item;
 
    // inserting
    if (editedItem.ItemIndex == -1)
    {
        this.gridBids_Insert(sender, ev);
        return;
    }
 
    DataRow[] changedRows = this.bidsTable.Select("blockbidsegmentid=" + editedItem.OwnerTableView.DataKeyValues[editedItem.ItemIndex]["blockbidsegmentid"].ToString());
    bool editFlag = false;
 
    if (changedRows.Length != 1)
    {
        ev.Canceled = true;
        return;
    }
 
    Hashtable newValues = new Hashtable();
    ev.Item.OwnerTableView.ExtractValuesFromItem(newValues, editedItem);
 
    changedRows[0].BeginEdit();
 
    string carrier = ((TextBox)editedItem.FindControl("txtBidCarrier")).Text.ToUpper();
    //string carrier = newValues["carrier"].ToString();
    if (carrier != changedRows[0]["carrier"].ToString())
    {
        changedRows[0]["carrier"] = carrier;
        editFlag = true;
    }
    string flightnum = ((TextBox)editedItem.FindControl("txtBidFlightNum")).Text;
    if (flightnum != changedRows[0]["flightnum"].ToString())
    {
        changedRows[0]["flightnum"] = flightnum;
        editFlag = true;
    }
    string from = ((TextBox)editedItem.FindControl("txtBidFrom")).Text.ToUpper();
    if (from != changedRows[0]["fromairportcode"].ToString())
    {
        changedRows[0]["fromairportcode"] = from;
        editFlag = true;
    }
    string to = ((TextBox)editedItem.FindControl("txtBidTo")).Text.ToUpper();
    if (to != changedRows[0]["toairportcode"].ToString())
    {
        changedRows[0]["toairportcode"] = to;
        editFlag = true;
    }
    string cos = ((TextBox)editedItem.FindControl("txtBidCOS")).Text.ToUpper();
    if (cos != changedRows[0]["cos"].ToString())
    {
        changedRows[0]["cos"] = cos;
        editFlag = true;
    }
 
    TimeSpan departts = new TimeSpan(Int32.Parse((((RadMaskedTextBox)editedItem.FindControl("txtBidDepartTime")).Text).Substring(0, 2)), Int32.Parse((((RadMaskedTextBox)editedItem.FindControl("txtBidDepartTime")).Text).Substring(3)), 0);
    DateTime depart = ((DateTime)((RadDatePicker)editedItem.FindControl("txtBidDepartDate")).SelectedDate).Date + departts;
    if (changedRows[0]["departtime"].ToString().Length == 0 || (changedRows[0]["departtime"].ToString().Length > 0 && depart != DateTime.Parse(changedRows[0]["departtime"].ToString())))
    {
        changedRows[0]["departtime"] = depart;
        editFlag = true;
    }
 
    TimeSpan arrivets = new TimeSpan(Int32.Parse((((RadMaskedTextBox)editedItem.FindControl("txtBidArriveTime")).Text).Substring(0, 2)), Int32.Parse((((RadMaskedTextBox)editedItem.FindControl("txtBidArriveTime")).Text).Substring(3)), 0);
    DateTime arrive = ((DateTime)((RadDatePicker)editedItem.FindControl("txtBidArriveDate")).SelectedDate).Date + arrivets;
    if (changedRows[0]["arrivetime"].ToString().Length == 0 || (changedRows[0]["arrivetime"].ToString().Length > 0 && arrive != DateTime.Parse(changedRows[0]["arrivetime"].ToString())))
    {
        changedRows[0]["arrivetime"] = arrive;
        editFlag = true;
    }
 
    int seats = 0;
    string seatsString = ((RadNumericTextBox)editedItem.FindControl("txtBidSeats")).Text;
    if (seatsString.Length > 0) Int32.TryParse(seatsString, out seats);
    if ((seats == null && changedRows[0]["seats"] != null) || (seats != null && changedRows[0]["seats"] == null) ||
        (seats != null && changedRows[0]["seats"] != null && seats.ToString() != changedRows[0]["seats"].ToString())) changedRows[0]["seats"] = seats;
 
    string notes = ((RadTextBox)editedItem.FindControl("txtBidNotes")).Text.Trim();
    if (notes.Length > 0)
    {
        changedRows[0]["notes"] = changedRows[0]["notes"].ToString() + "\n" + DateTime.Now.ToString("ddMMMyy HH:mm") + ", " + this._User.UserName + ": " + notes.Replace("\r\n", "  ");
    }
 
    changedRows[0].EndEdit();
    this.bidsTable.AcceptChanges();
}
0
Tsvetina
Telerik team
answered on 15 Mar 2012, 11:17 AM
Hello Colin,

Maybe I misunderstood you, but sample code in the help article explicitly creates a new key value for the DataTable and the comments note that this should not be done in a scenario with a real DB. So, in case you create a new row in the DataTable, you need to create the keyvalue instead of trying to access it. Anyway, if you have solved the problem, this does not matter that much.

As for the RadTextBoxes issue, I put your code into a page and managed to get it running after a few minor changes but could not replicate the problem with the RadTextBoxes, all of them returned their current value, as input by the user. Can you confirm which version of RadControls you are using?
Also, you could consider opening a formal support ticket where you could send us a runnable project replicating the issue, so that we can help you resolve it faster.

Greetings,
Tsvetina
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
Colin
Top achievements
Rank 1
answered on 19 Mar 2012, 06:29 PM
Thanks again for replying.
If you look at the first block of C# code I posted in my original message, you'll see the insert functionality with a primary key field (which is, I assume, the same as a "keyvalue"). This primary key field is referenced in the update code I posted. And, no, I was only trying to get it to work with a local DataTable object, not directly with a remote database.
Best I can tell I'm on v 2011.3.1305.40.
0
Tsvetina
Telerik team
answered on 22 Mar 2012, 11:51 AM
Hello Colin,

If you still experience the described problems, would it be possible that you put together a runnable sample of your code and send it to us through the ticketing system? We will debug it and see if the problem is in our control or the code used. If this is not possible, you could paste a gathered up version of your latest code in a runnable form.

Greetings,
Tsvetina
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.
Tags
Grid
Asked by
Colin
Top achievements
Rank 1
Answers by
Princy
Top achievements
Rank 2
Colin
Top achievements
Rank 1
Tsvetina
Telerik team
Share this question
or