Fully functional RadGrid with add, update and delete that is inside a RadWindow

1 Answer 58 Views
Grid UI for ASP.NET AJAX in ASP.NET MVC Window
SSirica
Top achievements
Rank 2
Iron
Iron
Veteran
SSirica asked on 20 Oct 2021, 05:17 PM

I'm launching a Radwindow that contains a RadGrid.  All that is working fine.  Data displays no problem.  The problem is when I click the Edit or the Delete commands the window goes away.  Clicking those doesn't even execute the grids ItemCommand event.  

I tried the grid  on it's own sans having it in a window and it functioned as expected.  Here's my code:

ASPX

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="Test.aspx.vb" Inherits="OmniCare.Test" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <ajax:ScriptManager runat="server" ID="ScriptManager1" EnablePartialRendering="true" />

        <telerik:RadScriptBlock ID="RadScriptBlock1" runat="server">
            <script language="javascript" type="text/javascript">
                function OnClientclose(sender, eventArgs) {
                    var arg = eventArgs.get_argument();
                }
            </script>
        </telerik:RadScriptBlock>

        <telerik:RadAjaxManager ID="RadAjaxManager1" runat="server">
            <AjaxSettings>
                <telerik:AjaxSetting AjaxControlID="rgDeposits">
                    <UpdatedControls>
                        <telerik:AjaxUpdatedControl ControlID="rgDeposits" />
                    </UpdatedControls>
                </telerik:AjaxSetting>
                <telerik:AjaxSetting AjaxControlID="btnDeposit">
                    <UpdatedControls>
                        <telerik:AjaxUpdatedControl ControlID="rwDeposits" />
                    </UpdatedControls>
                </telerik:AjaxSetting>
                <telerik:AjaxSetting AjaxControlID="rwDeposits">
                    <UpdatedControls>
                        <telerik:AjaxUpdatedControl ControlID="rwDeposits" />
                    </UpdatedControls>
                </telerik:AjaxSetting>
            </AjaxSettings>
        </telerik:RadAjaxManager>

        <telerik:RadWindowManager ID="RadWindowManager1" runat="server" EnableViewState="False">
            <Windows>
                <telerik:RadWindow runat="server" ID="rwDeposits" OnClientClose="OnClientclose" VisibleStatusbar="False" Width="750px" Height="350px" CssClass="Padding">
                    <ContentTemplate>
                        <asp:Panel runat="server" HorizontalAlign="Center" Width="98%" CssClass="PanelFrame MainPanel" BackColor="#DFECFB" Height="98%">
                            <div class="General TopRound" style="width: 100%; background-color: #dcdcdc; border-bottom: 1px solid black;">
                                <asp:Label ID="Label2" runat="server" Text="Deposit Information" CssClass="Title" Width="100%"></asp:Label>
                            </div>
                            <telerik:RadGrid ID="rgDeposits" runat="server" Width="99%" AutoGenerateColumns="False" CellPadding="1" CellSpacing="1" AutoGenerateDeleteColumn="True" AutoGenerateEditColumn="False" CssClass="Center" GridLines="Both">
                                <MasterTableView GridLines="Both" DataKeyNames="CUST_DEP_ID">
                                    <HeaderStyle Font-Bold="True" />
                                    <Columns>
                                        <telerik:GridEditCommandColumn></telerik:GridEditCommandColumn>
                                        <telerik:GridBoundColumn DataField="CU_DEP_DATE" HeaderText="Date"></telerik:GridBoundColumn>
                                        <telerik:GridBoundColumn DataField="CU_DEP_DESC" HeaderText="Description"></telerik:GridBoundColumn>
                                        <telerik:GridBoundColumn DataField="CU_DEP_STAT" HeaderText="Stat">
                                            <ItemStyle HorizontalAlign="Center"></ItemStyle>
                                        </telerik:GridBoundColumn>
                                        <telerik:GridBoundColumn DataField="CU_DEP_SIGN" HeaderText="Sign">
                                            <ItemStyle HorizontalAlign="Center" CssClass="Align-Center"></ItemStyle>
                                            <HeaderStyle HorizontalAlign="Center" CssClass="Align-Center" />
                                        </telerik:GridBoundColumn>
                                        <telerik:GridBoundColumn DataField="CU_DEP_AMT" HeaderText="Amount" DataFormatString="{0:c}">
                                            <ItemStyle HorizontalAlign="Right" CssClass="Align-Right"></ItemStyle>                                            
                                            <HeaderStyle HorizontalAlign="Center" CssClass="Align-Center" />
                                        </telerik:GridBoundColumn>
                                        <telerik:GridBoundColumn DataField="USER_LOGIN" HeaderText="OPR"></telerik:GridBoundColumn>
                                        <telerik:GridBoundColumn DataField="cu_dep_type_id" HeaderText="OPR" Visible="False"></telerik:GridBoundColumn>
                                    </Columns>
                                </MasterTableView>
                            </telerik:RadGrid>
                        </asp:Panel>
                    </ContentTemplate>
                </telerik:RadWindow>
            </Windows>
        </telerik:RadWindowManager>


        <div>
            <telerik:RadButton ID="btnDeposit" runat="server" Text="Deposit Detail" Width="100px" RenderMode="Lightweight" CssClass="center" 
                Font-Size="9px" CausesValidation="False" AutoPostBack="True" Height="27px">
                <Icon PrimaryIconUrl="Images/DollarSign.gif" PrimaryIconLeft="5px" PrimaryIconTop="8px"></Icon>
            </telerik:RadButton>

        </div>
    </form>
</body>
</html>

VB


Imports Telerik.Web.UI

Public Class Test
    Inherits System.Web.UI.Page

    Dim db As dcDataDataContext = Nothing

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        db = New dcDataDataContext("SAMP1")

    End Sub

    Private Sub rgDeposits_NeedDataSource(sender As Object, e As GridNeedDataSourceEventArgs) Handles rgDeposits.NeedDataSource
        Dim res = From x In db.sp_Cust_Dep_SEL(1)
                  Select x

        rgDeposits.DataSource = res.ToList

    End Sub


    Private Sub rgDeposits_ItemCommand(sender As Object, e As GridCommandEventArgs) Handles rgDeposits.ItemCommand
        Dim xxx As String = e.CommandName
    End Sub

    Private Sub btnDeposit_Click(sender As Object, e As EventArgs) Handles btnDeposit.Click
        rgDeposits.Rebind()

        Dim script As String = "function f(){$find(""" + rwDeposits.ClientID + """).show(); Sys.Application.remove_load(f);}Sys.Application.add_load(f);"
        ScriptManager.RegisterStartupScript(Page, Page.GetType(), "key", script, True)

    End Sub
End Class

SSirica
Top achievements
Rank 2
Iron
Iron
Veteran
commented on 25 Oct 2021, 12:42 PM

Did I stump you guys and gals?

1 Answer, 1 is accepted

Sort by
0
Accepted
Attila Antal
Telerik team
answered on 25 Oct 2021, 02:21 PM | edited on 25 Oct 2021, 03:45 PM

Hi Steve,

When you add a Control to the AjaxSettings, you must not add its Child controls again. For instance, you have the RadWindow "rwDeposits" is Ajaxified. Then its child control "rgDeposits" is also Ajaxified. This will create a nested Ajax structure that will cause issues. Check out the Understanding AJAX Controls to get a better understanding.

In case you are enabling AJAX for the Content of a RadWindow, I suggest that you Ajaxify the content right inside the ContentTemplate using RadAjaxPanels. In this case, however, you must not add any of the controls to the RadAjaxManager's AjaxSettings. WindowManager and Windows are Opening/Closing on clients, so they do not need to be Ajaxified.

<telerik:RadWindowManager ID="RadWindowManager1" runat="server">
    <Windows>

        <telerik:RadWindow ID="RadWindow1" runat="server">
            <ContentTemplate>

                <telerik:RadAjaxPanel ID="RadAjaxPanel1" runat="server" Height="200px" Width="300px">

                    <telerik:RadGrid ID="RadGrid1" runat="server"></telerik:RadGrid>

                </telerik:RadAjaxPanel>

            </ContentTemplate>
        </telerik:RadWindow>

    </Windows>
</telerik:RadWindowManager>

 

Update

UpdatePanel/RadAjaxPanel will not work if the RadWindow is inside a RadWindowManager. You can only Ajaxify content in the RadWindow if it's not part of the RadWindowManager. See How to Use RadWindow with AJAX.

Example:

<telerik:RadWindow ID="RadWindow2" runat="server">
    <ContentTemplate>

        <telerik:RadAjaxPanel ID="RadAjaxPanel2" runat="server" Height="200px" Width="300px">

            <telerik:RadGrid ID="RadGrid2" runat="server"></telerik:RadGrid>

        </telerik:RadAjaxPanel>

    </ContentTemplate>
</telerik:RadWindow>

 

This is guaranteed to be working.

 

You can try the following working example:

<telerik:RadWindow ID="RadWindow1" runat="server" VisibleOnPageLoad="true">
    <ContentTemplate>

        <telerik:RadAjaxPanel ID="RadAjaxPanel1" runat="server" Height="200px" Width="300px">

            <asp:Label ID="Label1" runat="server" Text="Action:"></asp:Label>
            <telerik:RadGrid ID="RadGrid1" runat="server" AllowPaging="True" Width="800px"
                AutoGenerateEditColumn="true"
                AutoGenerateDeleteColumn="true"
                OnNeedDataSource="RadGrid1_NeedDataSource"
                OnInsertCommand="RadGrid1_InsertCommand"
                OnUpdateCommand="RadGrid1_UpdateCommand"
                OnDeleteCommand="RadGrid1_DeleteCommand">

                <MasterTableView AutoGenerateColumns="False" DataKeyNames="OrderID" CommandItemDisplay="Top" InsertItemDisplay="Top" InsertItemPageIndexAction="ShowItemOnLastPage">
                    <Columns>
                        <telerik:GridBoundColumn DataField="OrderID" DataType="System.Int32"
                            FilterControlAltText="Filter OrderID column" HeaderText="OrderID"
                            ReadOnly="True" SortExpression="OrderID" UniqueName="OrderID">
                        </telerik:GridBoundColumn>
                        <telerik:GridDateTimeColumn DataField="OrderDate" DataType="System.DateTime"
                            FilterControlAltText="Filter OrderDate column" HeaderText="OrderDate"
                            SortExpression="OrderDate" UniqueName="OrderDate">
                        </telerik:GridDateTimeColumn>
                        <telerik:GridNumericColumn DataField="Freight" DataType="System.Decimal"
                            FilterControlAltText="Filter Freight column" HeaderText="Freight"
                            SortExpression="Freight" UniqueName="Freight">
                        </telerik:GridNumericColumn>
                        <telerik:GridBoundColumn DataField="ShipName"
                            FilterControlAltText="Filter ShipName column" HeaderText="ShipName"
                            SortExpression="ShipName" UniqueName="ShipName">
                        </telerik:GridBoundColumn>
                        <telerik:GridBoundColumn DataField="ShipCountry"
                            FilterControlAltText="Filter ShipCountry column" HeaderText="ShipCountry"
                            SortExpression="ShipCountry" UniqueName="ShipCountry">
                        </telerik:GridBoundColumn>
                    </Columns>
                </MasterTableView>
            </telerik:RadGrid>


        </telerik:RadAjaxPanel>

    </ContentTemplate>
</telerik:RadWindow>

 

C#

#region Properties for CRUD Operations
public DataTable SessionDataSource
{
    get
    {
        string sessionKey = "SessionDataSource";

        if (Session[sessionKey] == null || !IsPostBack)
        {
            Session[sessionKey] = OrdersTable();
        }
        return (DataTable)Session[sessionKey];
    }
}
#endregion

#region RadGrid Events for CRUD Operations

// CREATE (Add New Record)
protected void RadGrid1_InsertCommand(object sender, GridCommandEventArgs e)
{
    GridEditableItem editedItem = e.Item as GridEditableItem;

    DataRow newRow = SessionDataSource.NewRow();

    //As this example demonstrates only in-memory editing, a new primary key value should be generated
    //This should not be applied when updating directly the database
    DataRow[] allValues = SessionDataSource.Select("OrderID = MAX(OrderID)");

    if (allValues.Length > 0)
    {
        newRow["OrderID"] = int.Parse(allValues[0]["OrderID"].ToString()) + 1;
    }
    else
    {
        newRow["OrderID"] = 1; //the table is empty;
    }

    //Set new values
    Hashtable newValues = new Hashtable();
    //The GridTableView will fill the values from all editable columns in the hash
    e.Item.OwnerTableView.ExtractValuesFromItem(newValues, editedItem);

    try
    {
        foreach (DictionaryEntry entry in newValues)
        {
            newRow[(string)entry.Key] = entry.Value;
        }
    }
    catch (Exception ex)
    {
        Label1.Text += string.Format("<br />Unable to insert into Orders. Reason: {0}", ex.Message);
        e.Canceled = true;
        return;
    }

    SessionDataSource.Rows.Add(newRow);
    //Code for updating the database ca go here...
    Label1.Text += string.Format("<br />Order {0} inserted", newRow["OrderID"]);
}

// READ (data binding)
protected void RadGrid1_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
{
    (sender as RadGrid).DataSource = SessionDataSource;
}

// UPDATE
protected void RadGrid1_UpdateCommand(object sender, GridCommandEventArgs e)
{
    GridEditableItem editedItem = e.Item as GridEditableItem;

    //Locate the changed row in the DataSource
    DataRow[] changedRows = SessionDataSource.Select(string.Format("OrderID = {0}", editedItem.GetDataKeyValue("OrderID")));

    if (changedRows.Length != 1)
    {
        this.Label1.Text += "Unable to locate the Order for updating.";
        e.Canceled = true;
        return;
    }
    //Update new values
    Hashtable newValues = new Hashtable();
    e.Item.OwnerTableView.ExtractValuesFromItem(newValues, editedItem);
    changedRows[0].BeginEdit();
    try
    {
        foreach (DictionaryEntry entry in newValues)
        {
            changedRows[0][(string)entry.Key] = entry.Value;
        }
        changedRows[0].EndEdit();
    }
    catch (Exception ex)
    {
        changedRows[0].CancelEdit();
        Label1.Text += string.Format("Unable to update Orders. Reason: {0}", ex.Message);
        e.Canceled = true;
        return;
    }
}

// DELETE
protected void RadGrid1_DeleteCommand(object sender, GridCommandEventArgs e)
{
    GridDataItem dataItem = e.Item as GridDataItem;
    string ID = dataItem.GetDataKeyValue("OrderID").ToString();

    if (SessionDataSource.Rows.Find(ID) != null)
    {
        SessionDataSource.Rows.Find(ID).Delete();
    }
}
#endregion

#region DataSource
private DataTable OrdersTable()
{
    DataTable dt = new DataTable();

    dt.Columns.Add(new DataColumn("OrderID", typeof(int)));
    dt.Columns.Add(new DataColumn("OrderDate", typeof(DateTime)));
    dt.Columns.Add(new DataColumn("Freight", typeof(decimal)));
    dt.Columns.Add(new DataColumn("ShipName", typeof(string)));
    dt.Columns.Add(new DataColumn("ShipCountry", typeof(string)));

    dt.PrimaryKey = new DataColumn[] { dt.Columns["OrderID"] };

    for (int i = 0; i < 70; i++)
    {
        int index = i + 1;

        DataRow row = dt.NewRow();

        row["OrderID"] = index;
        row["OrderDate"] = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0).AddHours(index);
        row["Freight"] = index * 0.1 + index * 0.01;
        row["ShipName"] = "Name " + index;
        row["ShipCountry"] = "Country " + index;

        dt.Rows.Add(row);
    }

    return dt;
}
#endregion

 

VB

#Region "Properties for CRUD Operations"
    Public ReadOnly Property SessionDataSource() As DataTable
        Get
            Dim sessionKey As String = "SessionDataSource"
            If Session(sessionKey) Is Nothing Or Not IsPostBack Then
                Session(sessionKey) = OrdersTable()
            End If
            Return DirectCast(Session(sessionKey), DataTable)
        End Get
    End Property
#End Region

#Region "RadGrid Events for CRUD Operations"
    'CREATE (Add New Record)
    Protected Sub RadGrid1_InsertCommand(sender As Object, e As GridCommandEventArgs)
        Dim editedItem As GridEditableItem = CType(e.Item, GridEditableItem)

        'As this example demonstrates only in-memory editing, a new primary key value should be generated
        'This should not be applied when updating directly the database
        Dim allValues() As DataRow = SessionDataSource.Select("OrderID = MAX(OrderID)")

        Dim newRow As DataRow = SessionDataSource.NewRow

        If (allValues.Length > 0) Then
            newRow("OrderID") = Integer.Parse(allValues(0)("OrderID").ToString()) + 1
        Else
            newRow("OrderID") = 1
            'the table is empty;
        End If
        'Set new values
        Dim newValues As Hashtable = New Hashtable
        'The GridTableView will fill the values from all editable columns in the hash
        e.Item.OwnerTableView.ExtractValuesFromItem(newValues, editedItem)
        Try
            For Each entry As DictionaryEntry In newValues
                newRow(CType(entry.Key, String)) = entry.Value
            Next
        Catch ex As Exception
            Label1.Text &= String.Format("<br />Unable to insert into Orders. Reason: {0}", ex.Message)
            e.Canceled = True
            Return
        End Try
        SessionDataSource.Rows.Add(newRow)
        'Code for updating the database ca go here...

        Label1.Text &= String.Format("<br />Order {0} inserted", newRow("OrderID"))
    End Sub

    'READ (data binding)
    Protected Sub RadGrid1_NeedDataSource(sender As Object, e As GridNeedDataSourceEventArgs)
        RadGrid1.DataSource = SessionDataSource
    End Sub

    'UPDATE
    Protected Sub RadGrid1_UpdateCommand(sender As Object, e As GridCommandEventArgs)
        Dim editedItem As GridEditableItem = TryCast(e.Item, GridEditableItem)
        'Locate the changed row in the DataSource
        Dim changedRows As DataRow() = SessionDataSource.Select(String.Format("OrderID = {0}", editedItem.GetDataKeyValue("OrderID")))

        If changedRows.Length <> 1 Then
            Me.Label1.Text &= "<br />Unable to locate the Order for updating."
            e.Canceled = True
            Return
        End If

        'Update new values
        Dim newValues As New Hashtable()
        e.Item.OwnerTableView.ExtractValuesFromItem(newValues, editedItem)
        changedRows(0).BeginEdit()
        Try
            For Each entry As DictionaryEntry In newValues
                changedRows(0)(DirectCast(entry.Key, String)) = entry.Value
            Next
            changedRows(0).EndEdit()
        Catch ex As Exception
            changedRows(0).CancelEdit()
            Label1.Text &= String.Format("<br />Unable to update Orders. Reason: {0}", ex.Message)
            e.Canceled = True
            Return
        End Try
    End Sub

    'DELETE
    Protected Sub RadGrid1_DeleteCommand(sender As Object, e As GridCommandEventArgs)
        Dim dataItem = TryCast(e.Item, GridDataItem)
        Dim ID As String = dataItem.GetDataKeyValue("OrderID").ToString()

        If Not (SessionDataSource.Rows.Find(ID) Is Nothing) Then
            SessionDataSource.Rows.Find(ID).Delete()
        End If
    End Sub
#End Region

#Region "DataSource"
    Private Function OrdersTable() As DataTable
        Dim dt As New DataTable()

        dt.Columns.Add(New DataColumn("OrderID", Type.GetType("System.Int32")))
        dt.Columns.Add(New DataColumn("OrderDate", Type.GetType("System.DateTime")))
        dt.Columns.Add(New DataColumn("Freight", Type.GetType("System.Decimal")))
        dt.Columns.Add(New DataColumn("ShipName", Type.GetType("System.String")))
        dt.Columns.Add(New DataColumn("ShipCountry", Type.GetType("System.String")))

        Dim PrimaryKeyColumns As DataColumn() = New DataColumn(0) {}
        PrimaryKeyColumns(0) = dt.Columns("OrderID")
        dt.PrimaryKey = PrimaryKeyColumns

        For i As Integer = 0 To 70 - 1
            Dim index As Integer = i + 1
            Dim row As DataRow = dt.NewRow()

            row("OrderID") = index
            row("OrderDate") = New DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0).AddHours(index)
            row("Freight") = index * 0.1 + index * 0.01
            row("ShipName") = "Name " & index
            row("ShipCountry") = "Country " & index

            dt.Rows.Add(row)
        Next
        Return dt
    End Function
#End Region

 

 

Regards,
Attila Antal
Progress Telerik

Remote troubleshooting is now easier with Telerik Fiddler Jam. Get the full context to end-users' issues in just three steps! Start your trial here - https://www.telerik.com/fiddler-jam.
SSirica
Top achievements
Rank 2
Iron
Iron
Veteran
commented on 25 Oct 2021, 03:00 PM

Thanks but it didn't make a difference.  The window still went away when I clicked either the edit or the delete button on the grid.  
Attila Antal
Telerik team
commented on 25 Oct 2021, 03:46 PM

I have updated my answer. Check the "Update" section.
SSirica
Top achievements
Rank 2
Iron
Iron
Veteran
commented on 25 Oct 2021, 06:18 PM

It working.  It ended up being

  • No window Manager
  • Add RadAjaxPanel
  • Management of the VisibleOnPageLoad property.  Had to turn it on in launch button click

rwDeposits.VisibleOnPageLoad = "True"

Dim script AsString = "function f(){$find(""" + rwDeposits.ClientID + """).show(); Sys.Application.remove_load(f);}Sys.Application.add_load(f);" ScriptManager.RegisterStartupScript(Page, Page.GetType(), "key", script, True)

 

  • Turn it off on window close button click
rwDeposits.VisibleOnPageLoad = "false"

Dim script As String = "function f(){WinClose(); Sys.Application.remove_load(f);}Sys.Application.add_load(f);"
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "key", script, True)

Tags
Grid UI for ASP.NET AJAX in ASP.NET MVC Window
Asked by
SSirica
Top achievements
Rank 2
Iron
Iron
Veteran
Answers by
Attila Antal
Telerik team
Share this question
or