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

Insert, Update, and Delete firing but code not executing

2 Answers 91 Views
Grid
This is a migrated thread and some comments may be shown as answers.
John
Top achievements
Rank 1
John asked on 13 Feb 2013, 07:42 PM
I have a RadGrid and when I try to insert, update, or delete, the event fires and it moves into the code behind, but it stops executing the code before actually performing the action and reloads the page. My code behind is below. _config.Values is a DataTable. Filtering and sorting work fine.

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Linq.Dynamic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Telerik.Web.UI;
 
namespace WeightWatchers.EnvironmentConfig
{
    public partial class _Default : System.Web.UI.Page
    {
        private WeightWatchers.EnvironmentConfig.EnvironmentConfig _config;
        protected void Page_Load(object sender, EventArgs e)
        {
             
        }
 
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
 
            RadGrid1.NeedDataSource += (s, a) =>
            {
                _config = new EnvironmentConfig.EnvironmentConfig(MapPath(@".\App_Data\environment.config.csv"));
                if (RadGrid1.MasterTableView.SortExpressions.Count > 0)
                    RadGrid1.DataSource = GetEntities(RadGrid1.MasterTableView.FilterExpression,
                       RadGrid1.MasterTableView.SortExpressions[0].FieldName + " " + RadGrid1.MasterTableView.SortExpressions[0].SortOrderAsString());
                else
                    RadGrid1.DataSource = GetEntities(RadGrid1.MasterTableView.FilterExpression, "");
            };
 
            RadGrid1.UpdateCommand += (s, a) =>
            {
                //Get the GridEditableItem of the RadGrid    
                GridEditableItem editedItem = a.Item as GridEditableItem;
                string Name = editedItem.OwnerTableView.DataKeyValues[editedItem.ItemIndex]["Name"].ToString();
                try
                {
                    if (this.Validate(Name, true, editedItem))
                    {
                        this.UpdateAddRow(editedItem, true);
                        RadGrid1.DataSource = null;
                    }
                }
                catch (Exception ex)
                {
                    RadGrid1.Controls.Add(new LiteralControl("Unable to update Shippers. Reason: " + ex.Message));
                    a.Canceled = true;
                }
 
            };
 
            RadGrid1.InsertCommand += (s, a) =>
            {
                //Get the GridEditableItem of the RadGrid    
                GridEditableItem newItem = a.Item as GridEditableItem;
                string Name = (newItem["Name"].Controls[0] as TextBox).Text;
 
                try
                {
                    if (this.Validate(Name, false, newItem))
                    {
                        if (this.Validate(Name, true, newItem))
                        {
                            this.UpdateAddRow(newItem, false);
                            RadGrid1.DataSource = null;
                        }
                    }
                }
                catch (Exception ex)
                {
                    RadGrid1.Controls.Add(new LiteralControl("Unable to insert Shipper. Reason: " + ex.Message));
                    a.Canceled = true;
                }
 
            };
 
             
            RadGrid1.DeleteCommand += (s, a) =>
            {
                //Get the GridDataItem of the RadGrid    
                GridDataItem item = (GridDataItem)a.Item;
 
                //Get the primary key value using the DataKeyValue.    
                string name = item.OwnerTableView.DataKeyValues[item.ItemIndex]["Name"].ToString();
                try
                {
                    _config.Values.Rows.Remove(_config.Values.AsEnumerable()
                      .AsQueryable()
                      .Where(String.Format("(it[\"Name\"].ToString().ToUpper().Contains(\"{0}\".ToUpper()))", name))
                      .CopyToDataTable().Rows[0]);
                    RadGrid1.DataSource = null;
 
                }
                catch (Exception ex)
                {
                    RadGrid1.Controls.Add(new LiteralControl("Unable to delete Entry. Reason: " + ex.Message));
                    a.Canceled = true;
                }
         
            };
        }
 
        protected void RadGrid1_ItemCommand(object sender, GridCommandEventArgs e)
        {
            if (e.CommandName == "Filter" || e.CommandName == "Sort")
            {
                RadGrid1.DataSource = null;
            }
        }
 
        private DataTable GetEntities(string filterExpression, string sortExpression)
        {
            foreach (GridColumn col in RadGrid1.Columns)
            {
                col.AutoPostBackOnFilter = true;
            }
            var dt = _config.Values;
            if (!String.IsNullOrEmpty(filterExpression))
            {
                IQueryable<DataRow> rows = dt.AsEnumerable()
                 .AsQueryable()
                 .Where(filterExpression);
                 if (rows.Count<DataRow>() > 0)
                 {
                    dt = rows.CopyToDataTable();
                 }
                 else
                 {
                     dt.Clear();
                 }
            }
            if (!String.IsNullOrEmpty(sortExpression))
            {
                IQueryable<DataRow> rows = dt.AsEnumerable()
                 .AsQueryable()
                 .Where(sortExpression);
                if (rows.Count<DataRow>() > 0)
                {
                    dt = rows.CopyToDataTable();
                }
                else
                {
                    dt.Clear();
                }
            }
            return dt;
        }
 
        public void UpdateAddRow(GridEditableItem editedItem, bool update)
        {
            String[] cells = new String[_config.Values.Columns.Count];
            for (int i = 1; i < _config.Values.Columns.Count; i++)
            {
                cells[i]= (editedItem[_config.Values.Columns[i].ColumnName].Controls[0] as TextBox).Text;
            }
             
            if (update)
            {
                string Name = editedItem.OwnerTableView.DataKeyValues[editedItem.ItemIndex]["Name"].ToString();
 
                DataRow[] rows = _config.Values.Select(String.Format("Name = '{0}'", Name));
                var row = rows[0];
                for (int i = 1; i < _config.Values.Columns.Count; i++)
                {
                    row[_config.Values.Columns[i].ColumnName] = cells[i];
                }
 
            }
            else
            {
                cells[0] = (editedItem["Name"].Controls[0] as TextBox).Text;
                var row = _config.Values.NewRow();
                for (int i = 1; i < _config.Values.Columns.Count; i++)
                {
                    row[_config.Values.Columns[i].ColumnName] = cells[i];
                }
 
                _config.Values.Rows.Add(row);
            }
            RadGrid1.DataSource = null;
        }
 
        public bool Validate(string name, bool placeholder, GridEditableItem editedItem)
        {
            bool valid = true;
            //if (placeholder)
            //{
            //    string pattern = "";
            //    foreach (TableCell item in editedItem.Cells)
            //    {
            //        if (System.Text.RegularExpressions.Regex.IsMatch(item.Text, pattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase))
            //        {
            //            if (!item.ID.Equals("Name"))
            //            {
            //                valid = _config.Validate(item.Text, placeholder);
            //            }
            //        }
            //    }
            //}
            //else
            //{
            //    valid = _config.Validate(name, placeholder);
            //}
            return valid;
        }
    }
}

2 Answers, 1 is accepted

Sort by
0
John
Top achievements
Rank 1
answered on 13 Feb 2013, 08:29 PM
I should also mention that I just tried replacing my delete code with this line of code to just remove the first line of the DataTable.
_config.Values.Rows.RemoveAt(0);

Nothing happens still. It gets to the delete line then just sends the Ajax response for the entire page as it is currently without executing the delete code.
0
Angel Petrov
Telerik team
answered on 18 Feb 2013, 01:17 PM
Hi John,

Could you please clarify where the _config.values is stored? If it is not populated when you delete a record you will receive an exception. Please elaborate more on your scenario so we could advise you further. Also try debugging your code and inspect the _config.values to see if it is populated.

Regards,
Angel Petrov
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
John
Top achievements
Rank 1
Answers by
John
Top achievements
Rank 1
Angel Petrov
Telerik team
Share this question
or