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

RadGrid KeyValues always empty

2 Answers 380 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Adam
Top achievements
Rank 1
Adam asked on 11 Jun 2008, 04:49 PM

My partner and I have been struggling for a long while with this problem.  Based off of the code supplied by Telerik, I have two custom input forms for a RadGrid, one for inserts, one for edits.  When the code gets to pulling the DataKeyValues from the grid of old values, the code always throws an ArgumentOutOfBoundsException and does not pick up any values.  Seems like they're there before the update, then they disappear at update time.

Inserts work fine, but deleting and updating are breaking the same way.

Here's the source: 

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> 
 
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %> 
 
<%@ Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" %> 
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml">  
<head runat="server">  
    <title>Untitled Page</title> 
</head> 
<body> 
    <form id="form1" runat="server">  
        <asp:ScriptManager ID="ScriptManager1" runat="server" /> 
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">  
            <ContentTemplate> 
                <asp:Panel ID="TitlePanel" runat="server" Height="23px" Width="825px" style="background-color:Black;color:GrayText; vertical-align:middle;font-size:10pt;font-family:Arial;">  
                    <asp:ImageButton ID="ImageButton1" ImageUrl="images/minussign.gif" runat="server" Height="20px" Width="25px" AccessKey="1" style="position:relative;top:2px;" /> 
                    <asp:Label ID="TitleLabel" runat="server" style="position:relative;top:-4px;"></asp:Label> 
                </asp:Panel> 
                <asp:Panel ID="ContentPanel" runat="server" style="background-color:Gray;width:825px;">                  
                    <telerik:RadGrid ID="RadGrid1" runat="server" AllowPaging="True" AutoGenerateEditColumn="True" GridLines="None" OnNeedDataSource="RadGrid1_NeedDataSource" OnDeleteCommand="RadGrid1_DeleteCommand" OnInsertCommand="RadGrid1_InsertCommand" OnItemCommand="RadGrid1_ItemCommand" OnUpdateCommand="RadGrid1_UpdateCommand" Width="825px" AllowAutomaticDeletes="True" AllowAutomaticInserts="True" AllowAutomaticUpdates="True" AutoGenerateColumns="False" AutoGenerateDeleteColumn="True">  
                        <MasterTableView CommandItemDisplay="Top">  
                            <Columns> 
                              <telerik:GridBoundColumn UniqueName="SID" HeaderText="SID" DataField="SID">                              
                              </telerik:GridBoundColumn> 
                              <telerik:GridBoundColumn UniqueName="Title" HeaderText="Title" DataField="TITLE">                              
                              </telerik:GridBoundColumn> 
                              <telerik:GridBoundColumn UniqueName="Name" HeaderText="Name" DataField="NAME">                              
                              </telerik:GridBoundColumn> 
                              <telerik:GridBoundColumn UniqueName="Product" HeaderText="Product" DataField="PRODUCT">                              
                              </telerik:GridBoundColumn> 
                              <telerik:GridBoundColumn UniqueName="SubmitDate" HeaderText="Submit Date" DataField="SUBMITDATE">                              
                              </telerik:GridBoundColumn> 
                              <telerik:GridBoundColumn UniqueName="Story" HeaderText="Story" DataField="STORY">                              
                              </telerik:GridBoundColumn> 
                            </Columns> 
                            <RowIndicatorColumn Visible="False">  
                                <HeaderStyle Width="20px" /> 
                            </RowIndicatorColumn> 
                            <ExpandCollapseColumn Resizable="False" Visible="False">  
                                <HeaderStyle Width="20px" /> 
                            </ExpandCollapseColumn> 
                            <EditFormSettings EditFormType="WebUserControl" UserControlName="EditForm.ascx">  
                                <PopUpSettings ScrollBars="None" /> 
                            </EditFormSettings> 
                        </MasterTableView> 
                    </telerik:RadGrid> 
                </asp:Panel> 
                <cc1:CollapsiblePanelExtender ID="CollapseEx" runat="server" CollapseControlID="TitlePanel" CollapsedImage="images/plussign.gif" ExpandControlID="TitlePanel" ExpandedImage="images/minussign.gif" TextLabelID="TitleLabel" TargetControlID="ContentPanel" ImageControlID="ImageButton1" CollapsedText="Click or press Alt-1 to expand<br />" ExpandedText="Click or press Alt-1 to collapse<br />">  
                </cc1:CollapsiblePanelExtender> 
            </ContentTemplate> 
        </asp:UpdatePanel> 
        <br /> 
        &nbsp;  
        <div> 
        </div> 
    </form> 
</body> 
</html> 
 


using System;  
using System.Data;  
using System.Collections;  
using System.Configuration;  
using System.Web;  
using System.Web.Security;  
using System.Web.UI;  
using System.Web.UI.WebControls;  
using System.Web.UI.WebControls.WebParts;  
using System.Web.UI.HtmlControls;  
using System.Data.SqlClient;  
using System.Data.OracleClient;  
 
using Telerik.Web.UI;  
 
public partial class _Default : System.Web.UI.Page   
{  
    OracleConnection ociConn = new OracleConnection("Data Source=localhost;Persist Security Info=True;User ID=system;Password=testdb;Unicode=True");  
 
    protected void RadGrid1_PreRender(object sender, System.EventArgs e)  
    {  
        if (!this.IsPostBack)  
        {  
            this.RadGrid1.MasterTableView.Items[1].Edit = true;  
            this.RadGrid1.MasterTableView.Rebind();  
        }  
    }  
 
 
    protected DataTable GetDataTable(string query) {  
 
        ociConn.Open();  
        OracleCommand cmd = new OracleCommand("Select SID, Title, Name, Product, SubmitDate, Story from Stories", ociConn);  
        DataTable temp = new DataTable();  
        OracleDataAdapter da = new OracleDataAdapter(cmd);  
 
        try {  
            da.Fill(temp);  
        }  
        finally {  
            ociConn.Close();  
        }  
 
        return temp;  
    }  
 
    private DataTable Stories  
    {  
        get 
        {  
            object obj = this.Session["Stories"];  
            if ((!(obj == null)))  
            {  
                return ((DataTable)(obj));  
            }  
            DataTable myDataTable = new DataTable();  
            myDataTable = GetDataTable("");  
            this.Session["Stories"] = myDataTable;  
            return myDataTable;  
        }  
    }  
 
 
    protected void  Page_Load(object sender, EventArgs e)  
    {  
 
    }  
 
 
    protected void RadGrid1_NeedDataSource(object source, Telerik.Web.UI.GridNeedDataSourceEventArgs e)  
    {  
 
        RadGrid1.DataSource = this.Stories;  
    }  
 
    protected void RadGrid1_InsertCommand(object source, GridCommandEventArgs e)  
    {  
        GridEditableItem editedItem = e.Item as GridEditableItem;  
        UserControl userControl = (UserControl)e.Item.FindControl(GridEditFormItem.EditFormUserControlID);  
 
        //Create new row in the DataSource          
        DataRow newRow = this.Stories.NewRow();  
 
        //Insert new values  
        Hashtable newValues = new Hashtable();  
 
        newValues["SID"] = Int32.Parse((userControl.FindControl("TextBox1"as TextBox).Text);  
        //newValues["Region"] = (userControl.FindControl("TextBox3") as TextBox).Text;  
        newValues["Title"] = (userControl.FindControl("TextBox2"as TextBox).Text;  
        newValues["Name"] = (userControl.FindControl("TextBox3"as TextBox).Text;  
        newValues["Product"] = "";  
        newValues["SubmitDate"] = DateTime.Now;  
        newValues["Story"] = "";  
 
        //newValues["City"] = (userControl.FindControl("TextBox2") as TextBox).Text;  
        //newValues["Region"] = (userControl.FindControl("TextBox3") as TextBox).Text;  
          
        try 
        {  
            foreach (DictionaryEntry entry in newValues)  
            {  
                newRow[(string)entry.Key] = entry.Value;  
            }  
            this.Stories.Rows.Add(newRow);  
            this.Stories.AcceptChanges();  
        }  
        catch (Exception ex)  
        {  
            RadGrid1.Controls.Add(new LiteralControl("Unable to update/insert Employees. Reason: " + ex.Message));  
            e.Canceled = true;  
        }  
    }  
 
    protected void RadGrid1_UpdateCommand(object source, GridCommandEventArgs e)  
    {  
 
        GridEditableItem editedItem = e.Item as GridEditableItem;  
 
        UserControl userControl = (UserControl)e.Item.FindControl(GridEditFormItem.EditFormUserControlID);  
 
        //Prepare new row to add it in the DataSource  
 
        DataRow[] changedRows = this.Stories.Select("SID = " + editedItem.OwnerTableView.DataKeyValues[editedItem.ItemIndex]["SID"]);  
        if (changedRows.Length != 1)  
        {  
            RadGrid1.Controls.Add(new LiteralControl("Unable to locate the Story for updating."));  
            e.Canceled = true;  
            return;  
        }  
 
        //Update new values  
        Hashtable newValues = new Hashtable();  
 
        newValues["SID"] = (userControl.FindControl("TextBox1"as TextBox).Text;  
        newValues["Title"] = (userControl.FindControl("TextBox2"as TextBox).Text;  
        newValues["Name"] = (userControl.FindControl("TextBox3"as TextBox).Text;  
        newValues["Product"] = (userControl.FindControl("TextBox4"as TextBox).Text;  
        newValues["SubmitDate"] = (userControl.FindControl("TextBox5"as TextBox).Text;  
        newValues["Story"] = (userControl.FindControl("TextBox6"as DropDownList).Text;  
 
        changedRows[0].BeginEdit();  
        try 
        {  
            foreach (DictionaryEntry entry in newValues)  
            {  
                changedRows[0][(string)entry.Key] = entry.Value;  
            }  
            changedRows[0].EndEdit();  
            this.Stories.AcceptChanges();  
        }  
        catch (Exception ex)  
        {  
            changedRows[0].CancelEdit();  
            RadGrid1.Controls.Add(new LiteralControl("Unable to update Stories. Reason: " + ex.Message));  
            e.Canceled = true;  
        }  
    }  
 
 
 
    protected void RadGrid1_DeleteCommand(object source, GridCommandEventArgs e)  
    {  
        string ID = (e.Item as GridDataItem).OwnerTableView.DataKeyValues[e.Item.ItemIndex]["SID"].ToString();  
        DataTable employeeTable = this.Stories;  
        if (employeeTable.Rows.Find(ID) != null)  
        {  
            employeeTable.Rows.Find(ID).Delete();  
            employeeTable.AcceptChanges();  
        }  
    }  
 
 
    protected void RadGrid1_ItemCommand(object source, GridCommandEventArgs e)  
    {  
        if (e.CommandName == RadGrid.InitInsertCommandName)  
        {  
 
            e.Canceled = true;  
            RadGrid1.EditIndexes.Clear();  
 
            e.Item.OwnerTableView.EditFormSettings.UserControlName = "AddForm.ascx";  
            e.Item.OwnerTableView.InsertItem();  
        }  
        else if (e.CommandName == RadGrid.EditCommandName)  
        {  
            e.Item.OwnerTableView.IsItemInserted = false;  
            e.Item.OwnerTableView.EditFormSettings.UserControlName = "EditForm.ascx";  
        }  
    }  

2 Answers, 1 is accepted

Sort by
0
Accepted
Princy
Top achievements
Rank 2
answered on 12 Jun 2008, 07:40 AM
Hi Adam,

Try setting the following properties to false and see  whether it is working.

ASPX:
AllowAutomaticDeletes="False"   
AllowAutomaticInserts="False"   
AllowAutomaticUpdates="False" 


Thanks
Princy.
0
Adam
Top achievements
Rank 1
answered on 14 Aug 2008, 12:26 PM

I'm sorry, I think I simply didn't set the DataKeyValues property to any actual values, so of course, the KeyValues will be returned empty.

Thanks a lot.

Adam.g
Tags
Grid
Asked by
Adam
Top achievements
Rank 1
Answers by
Princy
Top achievements
Rank 2
Adam
Top achievements
Rank 1
Share this question
or