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

Problem locating user control

7 Answers 119 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Matt
Top achievements
Rank 1
Matt asked on 16 Feb 2011, 04:26 PM
I am currently using a trial version of the Telerik RadControls for ASP.NET AJAX.

I have created a grid and I am using a usercontrol to display my edit form for the grid.

Editing records in the grid works fine, using the following code...

protected void SectionGrid_UpdateCommand(object source, GridCommandEventArgs e)
{
   UserControl userControl = (UserControl)e.Item.FindControl(GridEditFormItem.EditFormUserControlID);
   ...
   ...

However, I am getting problems when I try to create a new record in the database, using the following code:

protected void SectionGrid_InsertCommand(object source, GridCommandEventArgs e)
{
    UserControl userControl = (UserControl)e.Item.FindControl(GridEditFormItem.EditFormUserControlID);
    ...
    ...

In this second case, userControl always evaluates as NULL.

Can anyone see what I'm doing wrong?

Matt.

7 Answers, 1 is accepted

Sort by
0
Elliott
Top achievements
Rank 2
answered on 16 Feb 2011, 10:49 PM
is that the right cast for an insert?  perhaps there is a GridInsertFormItem or something of the same sort
when I work with user controls, the code behind of the user control which contains the functionality - it is addressed by properties
I can send you a fairly simple example
0
Matt
Top achievements
Rank 1
answered on 17 Feb 2011, 09:46 AM
Hi Marianne,

Thanks for the reply.

It seems to be the right cast - Telerik's example uses it:

http://demos.telerik.com/aspnet-ajax/grid/examples/dataediting/usercontroleditform/defaultcs.aspx
0
Martin
Telerik team
answered on 21 Feb 2011, 08:57 AM
Hello Matt,

Could you please confirm that you are using EditForms or Popup edit mode of your table view? Here is a small quote form our documentation:

When the EditMode property of a table view is "EditForms" or "PopUp", the table view's EditFormSettings property lets you configure the edit form. One of the EditFormSettings sub-properties is EditFormType, which lets you specify whether you want to use the built-in edit form or substitute your own custom edit form.

There are three possible settings for EditFormType:

  • AutoGenerated: When EditFormType is "AutoGenerated", the table view uses the built-in edit form.
  • WebUserControl: When EditFormType is "WebUserControl", you can supply a UserControl that the table view uses as an edit form.
  • Template: When EditFormType is "Template", you can supply a template that the table view uses to generate the edit form.

I hope this helps.

Kind regards,
Martin
the Telerik team
0
Matt
Top achievements
Rank 1
answered on 21 Feb 2011, 09:45 AM
Hi Martin,

I'm using:

<EditFormSettings UserControlName="MaintainSection.ascx" EditFormType="WebUserControl">

Thanks.

Matt.
0
Matt
Top achievements
Rank 1
answered on 22 Feb 2011, 03:05 PM
Hi Martin,

Can you have a look at this - I assume I'm doing something wrong, but I can't see what:

ModifyModule.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ModifyModule.aspx.cs" Inherits="ModifyModule" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<head id="Head1" runat="server">
    <title></title>
    <telerik:RadStyleSheetManager id="RadStyleSheetManager1" runat="server" />
     
</head>
<body>
    <form id="form1" runat="server">
    <telerik:RadScriptManager ID="RadScriptManager1" runat="server">
        <Scripts>
            <%--Needed for JavaScript IntelliSense in VS2010--%>
            <%--For VS2008 replace RadScriptManager with ScriptManager--%>
            <asp:ScriptReference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.Core.js" />
            <asp:ScriptReference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.jQuery.js" />
            <asp:ScriptReference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.jQueryInclude.js" />
        </Scripts>
    </telerik:RadScriptManager>
    <script type="text/javascript">
        //Put your JavaScript code here.
    </script>
 
 
    <telerik:RadAjaxManager ID="RadAjaxManager1" runat="server">
        <AjaxSettings>
            <telerik:AjaxSetting AjaxControlID="SectionGrid">
                <UpdatedControls>
                    <telerik:AjaxUpdatedControl ControlID="SectionGrid" />
                </UpdatedControls>
            </telerik:AjaxSetting>
        </AjaxSettings>
    </telerik:RadAjaxManager>
 
 
  
    <telerik:RadSkinManager ID="RadSkinManager1" Runat="server" Skin="Vista">
    </telerik:RadSkinManager>
     
     
    <telerik:RadAjaxPanel ID="RadAjaxPanel1" runat="server" Height="429px"
        Width="515px">
         
    <telerik:RadFormDecorator ID="RadFormDecorator1" runat="server" Skin="Vista" />
 
                         
    <br />
 
    <telerik:RadGrid ID="SectionGrid" runat="server" GridLines="Horizontal" Culture="en-GB"
        DataSourceID="ProjectAzureDataSource" AutoGenerateColumns="False"
        Width="897px" ondeletecommand="SectionGrid_DeleteCommand"
        onupdatecommand="SectionGrid_UpdateCommand"
        oninsertcommand="SectionGrid_InsertCommand"
        onrowdrop="SectionGrid_RowDrop" EnableViewState="True">
 
        <ClientSettings AllowRowsDragDrop="true">
            <Selecting AllowRowSelect="True" EnableDragToSelectRows="false" />
        </ClientSettings>
 
        <MasterTableView CommandItemDisplay="Top" DataSourceID="ProjectAzureDataSource"
            DataKeyNames="idSectionList" EnableViewState="True">
  
            <CommandItemTemplate>
            <div style="padding: 5px 5px;">
                <asp:LinkButton ID="btnEditSelected" runat="server" CommandName="EditSelected" Visible='<%# SectionGrid.EditIndexes.Count == 0 %>'><img style="border:0px;vertical-align:middle;" alt="" src="Images/Edit.gif" />Edit Selected Section</asp:LinkButton>  
                <asp:LinkButton ID="btnUpdateEdited" runat="server" CommandName="UpdateEdited" Visible='<%# SectionGrid.EditIndexes.Count > 0 %>'><img style="border:0px;vertical-align:middle;" alt="" src="Images/Update.gif" />Update</asp:LinkButton>  
                <asp:LinkButton ID="btnCancel" runat="server" CommandName="CancelAll" Visible='<%# SectionGrid.EditIndexes.Count > 0 || SectionGrid.MasterTableView.IsItemInserted %>'><img style="border:0px;vertical-align:middle;" alt="" src="Images/Cancel.gif" />Cancel Editing</asp:LinkButton>  
                <asp:LinkButton ID="btnInitInsert" runat="server" CommandName="InitInsert" Visible='<%# !SectionGrid.MasterTableView.IsItemInserted %>'><img style="border:0px;vertical-align:middle;" alt="" src="Images/AddRecord.gif" />Add New Section</asp:LinkButton>  
                <asp:LinkButton ID="btnPerformInsert" runat="server" CommandName="PerformInsert" Visible='<%# SectionGrid.MasterTableView.IsItemInserted %>'><img style="border:0px;vertical-align:middle;" alt="" src="Images/Insert.gif" /> Add This Section</asp:LinkButton>  
                <asp:LinkButton ID="btnDelete" OnClientClick="javascript:return confirm('Delete the selected section?')" runat="server" CommandName="DeleteSelected"><img style="border:0px;vertical-align:middle;" alt="" src="Images/Delete.gif" />Delete Selected Section</asp:LinkButton>  
                <asp:LinkButton ID="btnRebindGrid" runat="server" CommandName="RebindGrid"><img style="border:0px;vertical-align:middle;" alt="" src="Images/Refresh.gif" />Refresh Section List</asp:LinkButton>
            </div>
            </CommandItemTemplate>
                            
            <CommandItemSettings ExportToPdfText="Export to Pdf" />
                           
            <RowIndicatorColumn FilterControlAltText="Filter RowIndicator column">
                <HeaderStyle Width="20px" />
            </RowIndicatorColumn>
            <ExpandCollapseColumn FilterControlAltText="Filter ExpandColumn column">
                <HeaderStyle Width="20px" />
            </ExpandCollapseColumn>
            <Columns>
                <telerik:GridBoundColumn DataField="idSectionList" DataType="System.Int32"
                    FilterControlAltText="Filter idSectionList column" HeaderText="idSectionList"
                    ReadOnly="True" SortExpression="idSectionList" UniqueName="idSectionList"
                    Visible="False">
                </telerik:GridBoundColumn>
                <telerik:GridBoundColumn DataField="sectionPosition" DataType="System.Int32"
                    FilterControlAltText="Filter sectionPosition column" HeaderText="sectionPosition"
                    SortExpression="sectionPosition" UniqueName="sectionPosition"
                    ReadOnly="True" Visible="False">
                </telerik:GridBoundColumn>
                <telerik:GridBoundColumn DataField="sectionName"
                    FilterControlAltText="Filter sectionName column" HeaderText="Section Name"
                    SortExpression="sectionName" UniqueName="sectionName" MaxLength="100" >
                    <HeaderStyle Width="100%" />
                </telerik:GridBoundColumn>
            </Columns>
                          
  
            <EditFormSettings UserControlName="MaintainSection.ascx" EditFormType="WebUserControl">
                <EditColumn UniqueName="SectionEditColumn">
                </EditColumn>
            </EditFormSettings>
 
                       
        </MasterTableView>
                             
 
        <FilterMenu EnableImageSprites="False"></FilterMenu>
 
        <HeaderContextMenu CssClass="GridContextMenu GridContextMenu_Default"></HeaderContextMenu>
 
    </telerik:RadGrid>
 
 
 
    <asp:SqlDataSource ID="ProjectAzureDataSource" runat="server"
        ConnectionString="<%$ ConnectionStrings:ProjectAzureConnectionString %>"
        SelectCommand="SELECT [idSectionList], [sectionPosition], [sectionName] FROM [sectionList] WHERE ([idModuleList] = 1) ORDER BY [sectionPosition]">
    </asp:SqlDataSource>
 
 
 
 
 
     
    </telerik:RadAjaxPanel>
 
 
     
 
    </form>
</body>
</html>

ModifyModule.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using Telerik.Web.UI;
 
public partial class ModifyModule : System.Web.UI.Page
{
 
    //Declare a global DataTable dtTable    
    public static DataTable dtTable;
    //Get the connectionstring from the webconfig and declare a global SqlConnection "SqlConnection"    
    public static string connectionString = ConfigurationManager.ConnectionStrings["ProjectAzureConnectionString"].ConnectionString;
    public SqlConnection SqlConnection = new SqlConnection(connectionString);
    //Declare a global SqlDataAdapter SqlDataAdapter    
    public SqlDataAdapter SqlDataAdapter = new SqlDataAdapter();
    //Declare a global SqlCommand SqlCommand    
    public SqlCommand SqlCommand = new SqlCommand();
 
 
 
 
    protected void Page_Load(object sender, EventArgs e)
    {
 
    }
 
 
    protected void SectionGrid_InsertCommand(object source, GridCommandEventArgs e)
    {
        UserControl userControl = (UserControl)e.Item.FindControl(GridEditFormItem.EditFormUserControlID);
                 
        //Get the GridEditFormInsertItem of the RadGrid    
        //GridEditFormInsertItem insertedItem = e.Item as GridEditFormInsertItem;
 
        string sectionName = (userControl.FindControl("sectionName") as TextBox).Text.Trim();
        sectionName = sectionName.Replace("'", "''");
 
        //string sectionName = (insertedItem.FindControl("sectionName") as TextBox).Text.Trim();
        //string sectionName = (insertedItem["sectionName"].Controls[0] as TextBox).Text.Trim();
 
        try
        {
            //Open the SqlConnection    
            SqlConnection.Open();
            //Update Query to insert into  the database     
            string insertQuery = "INSERT INTO  sectionList(idModuleList,sectionPosition,sectionName) VALUES (" + "1" + "," + "99" + ",'" + sectionName +  "')";
            SqlCommand.CommandText = insertQuery;
            SqlCommand.Connection = SqlConnection;
            SqlCommand.ExecuteNonQuery();
            //Close the SqlConnection    
            SqlConnection.Close();
 
        }
        catch (Exception ex)
        {
            SectionGrid.Controls.Add(new LiteralControl("Unable to insert section. Reason: " + ex.Message));
            e.Canceled = true;
        }
 
    }     
     
     
     
     
     
     
    protected void SectionGrid_DeleteCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
    {
        //Get the GridDataItem of the RadGrid    
        GridDataItem item = (GridDataItem)e.Item;
        //Get the primary key value using the DataKeyValue.    
        string idSectionList = item.OwnerTableView.DataKeyValues[item.ItemIndex]["idSectionList"].ToString();
        try
        {
            //Open the SqlConnection    
            SqlConnection.Open();
            string deleteQuery = "DELETE FROM sectionList WHERE idSectionList='" + idSectionList + "'";
            SqlCommand.CommandText = deleteQuery;
            SqlCommand.Connection = SqlConnection;
            SqlCommand.ExecuteNonQuery();
            //Close the SqlConnection    
            SqlConnection.Close();
 
        }
        catch (Exception ex)
        {
            SectionGrid.Controls.Add(new LiteralControl("Unable to delete section. Reason: " + ex.Message));
            e.Canceled = true;
        }
    }
 
    protected void SectionGrid_UpdateCommand(object source, GridCommandEventArgs e)
    {
        //Get the GridEditableItem of the RadGrid    
        GridEditableItem editedItem = e.Item as GridEditableItem;
        //Get the primary key value using the DataKeyValue.    
        string idSectionList = editedItem.OwnerTableView.DataKeyValues[editedItem.ItemIndex]["idSectionList"].ToString();
 
        UserControl userControl = (UserControl)e.Item.FindControl(GridEditFormItem.EditFormUserControlID);
 
        string sectionName = (userControl.FindControl("sectionName") as TextBox).Text.Trim();
        sectionName = sectionName.Replace("'", "''");
 
 
        try
        {
            //Open the SqlConnection    
            SqlConnection.Open();
            //Update Query to update the Datatable     
            string updateQuery = "UPDATE sectionList SET sectionName='" + sectionName + "' WHERE idSectionList='" + idSectionList + "'";
            SqlCommand.CommandText = updateQuery;
            SqlCommand.Connection = SqlConnection;
            SqlCommand.ExecuteNonQuery();
            //Close the SqlConnection    
            SqlConnection.Close();
 
        }
        catch (Exception ex)
        {
            SectionGrid.Controls.Add(new LiteralControl("Unable to update section. Reason: " + ex.Message));
             
        }
 
    }
 
 
    protected void SectionGrid_RowDrop(object sender, GridDragDropEventArgs e)
    {
        // Procedure to handle drag and drop re-ordering
 
        if (e.DestDataItem != null)
        {
            // Open the SqlConnection    
            SqlConnection.Open();
             
            // Get the id of the row to move, and its current position
            Int32 RowToMoveID = (int)e.DraggedItems.FirstOrDefault().GetDataKeyValue("idSectionList");
            string sqlCurrentPosition = "SELECT sectionPosition FROM sectionList WHERE idSectionList = " + RowToMoveID.ToString().Trim();
            SqlCommand.CommandText = sqlCurrentPosition;
            SqlCommand.Connection = SqlConnection;
            Int32 currentPosition = Convert.ToInt32(SqlCommand.ExecuteScalar());
 
            // Find out the new position
            Int32 RowDestinationID = (int)e.DestDataItem.GetDataKeyValue("idSectionList");
            string sqlNewPosition = "SELECT sectionPosition FROM sectionList WHERE idSectionList = " + RowDestinationID.ToString().Trim();
            SqlCommand.CommandText = sqlNewPosition;
            SqlCommand.Connection = SqlConnection;
            Int32 newPosition = Convert.ToInt32(SqlCommand.ExecuteScalar());
 
            if (currentPosition < newPosition)
            {
                newPosition -= 1;
            }
             
             
            if (e.DropPosition == GridItemDropPosition.Above)
            {
                newPosition -= 1;
            }
 
            if (e.DropPosition == GridItemDropPosition.Below)
            {
                newPosition += 1;
            }
 
             
            List<Int32> orderedSections = new List<Int32>();
             
 
 
            // Scan through the grid, picking up the id of each row and adding it to the ordered list
            foreach (GridDataItem dataItem in SectionGrid.Items)
            {
                Int32 idSectionList = (Int32)dataItem.GetDataKeyValue("idSectionList");
                orderedSections.Add(idSectionList);
            }
 
            // Remove the dragged section from the ordered List
            orderedSections.Remove(RowToMoveID);
 
            // Add the dragged section into its new position
            try
            {
                orderedSections.Insert(newPosition, RowToMoveID);
            }
            catch
            {
                orderedSections.Add(RowToMoveID);
            }
 
            // Variable to hold section position
            Int32 sectionPosition = 1;
 
            foreach (Int32 idSectionList in orderedSections)
            {
 
                // Update Query to update the Datatable     
                string updateQuery = "UPDATE sectionList SET sectionPosition=" + sectionPosition.ToString().Trim() + " WHERE idSectionList=" + idSectionList.ToString().Trim();
                SqlCommand.CommandText = updateQuery;
                SqlCommand.Connection = SqlConnection;
                SqlCommand.ExecuteNonQuery();
 
                // Increment the section position
                sectionPosition += 1;
 
            }
 
            //Close the SqlConnection
            SqlConnection.Close();
 
 
            SectionGrid.Rebind();
 
        }
 
    }
 
 
 
 
}

MaintainSection.ascx

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="MaintainSection.ascx.cs" Inherits="MaintainSection" %>
<%@ Register TagPrefix="telerik" Namespace="Telerik.Web.UI" Assembly="Telerik.Web.UI" %>
<table id="Table2" cellspacing="2" cellpadding="1" width="100%" border="1" rules="none"
    style="border-collapse: collapse">
    <tr class="EditFormHeader">
        <td colspan="2">
            <b>Section Name</b>
        </td>
    </tr>
 
    <tr>
        <td>
            <asp:TextBox ID="sectionName" runat="server"
                Text='<%# DataBinder.Eval( Container, "DataItem.sectionName" ) %>'
                Width="459px"></asp:TextBox>
        </td>
    </tr>
 
</table>

MaintainSection.ascx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
 
public partial class MaintainSection : System.Web.UI.UserControl
{
 
    private object _dataItem = null;
 
    protected void Page_Load(object sender, EventArgs e)
    {
 
    }
 
    public object DataItem
    {
        get
        {
            return this._dataItem;
        }
        set
        {
            this._dataItem = value;
        }
    }
 
}
0
Accepted
Princy
Top achievements
Rank 2
answered on 23 Feb 2011, 06:51 AM
Hello Matt,

Try the following code snippet inside InsertCommand to locate UserControl.

C#:
protected void SectionGrid_InsertCommand(object sender, GridCommandEventArgs e)
   {
       GridEditFormInsertItem insertItem = (GridEditFormInsertItem)SectionGrid.MasterTableView.GetInsertItem();
       UserControl userControl = (UserControl)insertItem.FindControl(GridEditFormItem.EditFormUserControlID);
       .     .    .     .    .    .    .    .
    }

Thanks,
Princy.
0
Matt
Top achievements
Rank 1
answered on 23 Feb 2011, 10:06 AM
Thanks very much Princy - that works great!
Tags
Grid
Asked by
Matt
Top achievements
Rank 1
Answers by
Elliott
Top achievements
Rank 2
Matt
Top achievements
Rank 1
Martin
Telerik team
Princy
Top achievements
Rank 2
Share this question
or