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

Getting updates from UserControl

5 Answers 110 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Fred
Top achievements
Rank 1
Fred asked on 29 Nov 2011, 11:17 PM
I have a grid with this line
<EditFormSettings UserControlName="editform.ascx" EditFormType="WebUserControl">

</EditFormSettings>
I hit the edit button and it displays like it should but I can't get to the data when I hit update. below are the ascx and ascx.cs files and the update function

 

protected void RadGridCabFolders_UpdateCommand(object source, GridCommandEventArgs e)
{
    //GridEditManager editMan = (e.Item as GridEditableItem).EditManager;
    GridEditableItem editedItem = e.Item as GridEditableItem;
    UserControl userControl = (UserControl)e.Item.FindControl(GridEditFormItem.EditFormUserControlID);
 
    string commandText = "UPDATE " + Page_Cab.CabRealName + " SET ";
    List<SqlParameter> paras = new List<SqlParameter>();
    int doc_id = (int)((GridEditableItem)e.Item).GetDataKeyValue(DOC_ID);
    varRadGridCabFoldersIndex = Convert.ToInt16(doc_id);
    foreach (GridColumn column in e.Item.OwnerTableView.RenderColumns)
    {
        if (column is IGridEditableColumn && column.UniqueName != LOC && column.UniqueName != DELETED)
        {
            IGridEditableColumn editableCol = (column as IGridEditableColumn);
            if (editableCol.IsEditable)
            {
                //IGridColumnEditor editor = editMan.GetColumnEditor(editableCol);
 
                if (column.UniqueName != DOC_ID && column.UniqueName.ToLower() != TIME_STAMP)
                {
                    commandText += " " + column.UniqueName + "=@" + column.UniqueName + ",";
                    Control editFormControl = ((userControl)).FindControl(column.UniqueName);
                    Type editformType = editFormControl.GetType();
                    object editorValue =
                        (editformType.Name == "TextBox") ? ((TextBox)editFormControl).Text :
                        (editformType.Name == "DropDownList") ? ((DropDownList)editFormControl).Text :
                        (editformType.Name == "RadMaskedTextBox") ? ((RadMaskedTextBox)editFormControl).Text :
                        (editformType.Name == "RadDatePicker") ? ((RadDatePicker)editFormControl).ToString() : (object)null;
                     
                    paras.Add(new SqlParameter(column.UniqueName, editorValue));
                }
            }
        }
    }
    commandText = commandText.Substring(0, commandText.Length - 1) + " where doc_id=" + doc_id;
    DbHelper.ExecuteDbNonQuery(Page_Dept.DeptRealName, commandText, paras.ToArrayNullIsEmpty());
    setDT();
    ViewState["GridData"] = folder_dt;
 
    if (ViewState["GridData"] != null)
    {
        RadGridCabFolders.DataSource = ViewState["GridData"];
    }
}

 

using System;
using System.Data;
using System.Collections;
using System.Web.UI;
using Telerik.Web.UI;
using System.Data;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Text.RegularExpressions;
using TreenoCsLib;
 
 
    public partial class editform : System.Web.UI.UserControl
    {
 
        private object _dataItem = null;
        public CabItem Page_Cab { get { return (CabItem)Session[SessionKeys.SelCab]; } set { Session[TreenoCsLib.SessionKeys.SelCab] = value; } }
        public DeptItem Page_Dept { get { return (DeptItem)Session[SessionKeys.SelDept]; } set { Session[SessionKeys.SelDept] = value; } }
 
        protected void Page_Load(object sender, System.EventArgs e)
        {
            if (DataItem != null)
            {
                string ConnString = (string)Session[TreenoCsLib.SessionKeys.SelDeptDbConnString];
                SqlConnection conn = new SqlConnection(ConnString);
                SqlDataAdapter adapter = new SqlDataAdapter();
                adapter.SelectCommand = new SqlCommand("select departmentid from departments where real_name='" + Page_Cab.CabRealName + "'", conn);
                conn.Open();
                SqlDataReader myReader = null;
                myReader = adapter.SelectCommand.ExecuteReader();
                myReader.Read();
                string departmentid = myReader["departmentid"].ToString();
                conn.Close();
                Control EditTable = FindControl("Table4");
                object[] editFormVals = ((System.Data.DataRowView)(DataItem)).Row.ItemArray;
                int i = 0;
                foreach (DataColumn colObj in ((DataRowView)(DataItem)).Row.Table.Columns)
                {
                    TableRow r = new TableRow();
                    string colName = colObj.ColumnName;
                    if (colName == "file_id" ||
                      colName == "document_id" ||
                      colName == "cabinet_id" ||
                      colName == "doc_id" ||
                      colName == "location" ||
                      colName == "deleted" ||
                      colName == "timestamp" ||
                      colName == "TimeStamp" ||
                      colName == "fsearch_id")
                    {
                    }
                    else
                    {
                        //need to look up required and regex
                        string ConnStringDoc = ConfigurationManager.ConnectionStrings["docutron"].ConnectionString;
                        SqlConnection connDoc = new SqlConnection(ConnStringDoc);
                        SqlDataAdapter adapterDoc = new SqlDataAdapter();
                        SqlDataReader myReaderDoc = null;
                        adapter.SelectCommand = new SqlCommand("SELECT required,regex FROM field_format where cabinet_id=" + departmentid + " and field_name='" + colName + "'", conn);
                        conn.Open();
                        myReader = adapter.SelectCommand.ExecuteReader();
                        string requiredField = "0";
                        string regExField = "";
                        if (myReader.HasRows)
                        {
                            myReader.Read();
                            requiredField = myReader["required"].ToString();
                            regExField = myReader["regex"].ToString();
                        }
                        conn.Close();
                        //need to look up dropdown list (
                        adapterDoc.SelectCommand = new SqlCommand("SELECT value FROM settings where k='dt," + Page_Dept.DeptRealName + "," + departmentid + "," + colName + "'", connDoc);
                        connDoc.Open();
                        myReaderDoc = adapterDoc.SelectCommand.ExecuteReader();
                        if (myReaderDoc.HasRows) //need dropdown
                        {
                            myReaderDoc.Read();
                            string pattern = ",,,(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))";
                            Regex rg = new Regex(pattern);
                            string[] dropdownlistArr = rg.Split(myReaderDoc["value"].ToString());
                            TableCell c = new TableCell();
                            DropDownList tb = new DropDownList();
 
                            ArrayList tocs = new ArrayList(dropdownlistArr);
                            tb.DataSource = tocs;
                            tb.DataBind();
 
 
 
                            if (editFormVals[i].ToString() == null)
                            {
                                tb.SelectedIndex = 0;
                            }
                            else
                            {
                                tb.SelectedIndex = tocs.IndexOf(editFormVals[i].ToString());
                            }
                            tb.DataSource = null;
 
 
                            tb.ID = colName;
                            //tb.Text = editFormVals[i].ToString();
                            c.Controls.Add(new LiteralControl(colName + ": "));
                            c.Controls.Add(tb);
                            r.Cells.Add(c);
                            ((Table)EditTable).Rows.Add(r);
                        }
                        else if (colName.Contains("date"))
                        {
                            TableCell c = new TableCell();
                            RadDatePicker tb = new RadDatePicker();
                            tb.ID = colName;
                            tb.DbSelectedDate = editFormVals[i].ToString();
                            c.Controls.Add(new LiteralControl(colName + ": "));
                            c.Controls.Add(tb);
                            r.Cells.Add(c);
                            ((Table)EditTable).Rows.Add(r);
                        }
                        else
                        {
                            TableCell c = new TableCell();
                            TextBox tb = new TextBox();
                            tb.ID = colName;
                            tb.Text = editFormVals[i].ToString();
                            c.Controls.Add(new LiteralControl(colName + ": "));
                            c.Controls.Add(tb);
                            r.Cells.Add(c);
                            ((Table)EditTable).Rows.Add(r);
                        }
                    }
                    ++i;
                }
            }
             //((System.Data.DataRowView)(DataItem)).Row.ItemArray
            //((System.Data.DataColumn)((new System.Collections.ArrayList.ArrayListDebugView(((System.Data.InternalDataCollectionBase)(((System.Data.DataRowView)(DataItem)).Row.Table.Columns)).List)).Items[0])).ColumnName
            // Put user code to initialize the page here
        }
 
        #region Web Form Designer generated code
        override protected void OnInit(EventArgs e)
        {
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            InitializeComponent();
            base.OnInit(e);
        }
         
        /// <summary>
        ///        Required method for Designer support - do not modify
        ///        the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.DataBinding += new System.EventHandler(this.EmployeeDetails_DataBinding);
 
        }
        #endregion
 
        public object DataItem
        {
            get
            {
                return this._dataItem;
            }
            set
            {
                this._dataItem = value;
            }
        }
 
        protected void EmployeeDetails_DataBinding(object sender, System.EventArgs e)
        {
            //ArrayList tocs = new ArrayList(new string[] { "Dr.", "Mr.", "Mrs.", "Ms." });
            //Control temp = FindControl("vendor");
            //((DropDownList)temp).DataSource = tocs;
            //((DropDownList)temp).DataBind();
 
            //object tocValue = DataBinder.Eval(DataItem, "vendor");
 
            //if (tocValue == DBNull.Value)
            //{
            //    tocValue = "Mrs.";
            //}
            //((DropDownList)temp).SelectedIndex = tocs.IndexOf((string)tocValue);
            //((DropDownList)temp).DataSource = null;
        }
 
    }

 

<%@ Control Language="c#" Inherits="editform" CodeFile="editform.ascx.cs" %>
<%@ Register TagPrefix="telerik" Namespace="Telerik.Web.UI" Assembly="Telerik.Web.UI" %>
<asp:table id="Table2" cellspacing="2" cellpadding="1" width="100%" style="border-collapse: collapse" runat="server">
    <asp:TableRow CssClass="EditFormHeader">
        <asp:TableCell ColumnSpan="2">
            <b>Edit Form</b>
        </asp:TableCell>
    </asp:TableRow>
    <asp:TableRow>
        <asp:TableCell ColumnSpan="2">
            <b>Test:</b>
        </asp:TableCell>
    </asp:TableRow>
    <asp:TableRow>
        <asp:TableCell>
            <asp:Table id="Table4" runat="server">
            </asp:Table>
        </asp:TableCell>
    </asp:TableRow>
     <asp:TableRow>
        <asp:TableCell HorizontalAlign="Right" ColumnSpan="2">
            <asp:Button ID="btnUpdate" Text="Update" runat="server" CommandName="Update" Visible='<%# !(DataItem is Telerik.Web.UI.GridInsertionObject) %>'>
            </asp:Button>
            <asp:Button ID="btnInsert" Text="Insert" runat="server" CommandName="PerformInsert" Visible='<%# DataItem is Telerik.Web.UI.GridInsertionObject %>'>
            </asp:Button>
              
            <asp:Button ID="btnCancel" Text="Cancel" runat="server" CausesValidation="False" CommandName="Cancel">
            </asp:Button>
        </asp:TableCell>
    </asp:TableRow>
</asp:table>

5 Answers, 1 is accepted

Sort by
0
Shinu
Top achievements
Rank 2
answered on 30 Nov 2011, 05:58 AM
Hello Fred,

Try the following code.
C#:
protected void RadGrid2_UpdateCommand(object sender, GridCommandEventArgs e)
{
  GridEditFormItem editItem = (GridEditFormItem)RadGrid2.MasterTableView.GetItems(GridItemType.EditFormItem)[editIndex];//getting edit row
  UserControl userControl = (UserControl)editItem.FindControl(GridEditFormItem.EditFormUserControlID);
  TextBox txtbox = (TextBox)userControl.FindControl("TextBox1");
  string value = txtbox.Text;
}

-Shinu.
0
Fred
Top achievements
Rank 1
answered on 30 Nov 2011, 02:55 PM
nope that didn't work. just to make sure what is editIndex supposed to be? I assumed it was the itemIndex but I also hardcoded it just incase. Please take a closer look at the code. the examples I saw do not generate the rows dynamically. I'm using an asp:Table
0
Andrey
Telerik team
answered on 05 Dec 2011, 12:38 PM
Hello Fred,

Please check this online demo which implements similar scenario to yours. Also note that, you need to use two-way data-binding for the controls in your edit form in order to get data from it. In the demo this is done by using TextBox controls. Additionally, you could check whether this line of code:

Control editFormControl = ((userControl)).FindControl(column.UniqueName);

returns something different than null value.


Best wishes,
Andrey
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
Fred
Top achievements
Rank 1
answered on 05 Dec 2011, 02:21 PM
That is the example I started with. The difference is that I have a dynamicly built table and your example does not. I noticed that when I build a table from the code behind using Control editFormControl = ((userControl)).FindControl(column.UniqueName); I get a null. I added a watch to see if they are there but could not find those controls when they are added dynamically (Code behind)
0
Andrey
Telerik team
answered on 06 Dec 2011, 02:15 PM
Hi Fred,

The approach you have to use with static and with dynamic columns is the same. But since all previous advices were not helpful future investigation won't be appropriate without runnable project.

Please open a format support ticket and send us a sample runnable project illustrating the issue and we will do our best to find the issue.


Regards,
Andrey
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
Fred
Top achievements
Rank 1
Answers by
Shinu
Top achievements
Rank 2
Fred
Top achievements
Rank 1
Andrey
Telerik team
Share this question
or