llblgenprodatasource.EntityCollection.Remove

Posts   
 
    
deathwish
User
Posts: 56
Joined: 07-Nov-2006
# Posted on: 07-Nov-2006 11:00:12   

Hi,

I am currently using LLBLGen 2.0.0.0 Demo in a .Net 2 web application that uses SQL 2005. The project references SD.LLBLGen.Pro.ORMSupportClasses.NET20.dll .

I have a llblgenprodatasource, self servicing, on the page that has a datacontainertype="EntityCollection" and the entitycollectiontypename="Data.CollectionClasses.CustomerCollection". There is a detailsview bound to the first item in the collection.

There is also a r.a.d grid outside of the detailsview that is bound to the CustomerOrdersCollection of the CustomerEntity from the above llblgenprodatasource. In this grid there are checkboxes where the user can select orders and click a "Remove" button.

When the user clicks "Remove", it runs through the grid and removes all the selected entities from the CustomerEntity.CustomerOrdersCollection from the llblgenprodatasource. The grid is rebound and the items have been removed. When i debug the code the CustomerEntity.CustomerOrdersCollection displays the correct count of items in the CustomersOrdersCollection as the items have been removed.

The problem comes in when i click update of the detailsview, the items that were removed from the CustomerEntity.CustomerOrdersCollection are not removed from the database.

If i use the same functionality and use CustomerOrdersCollection.Add() the items are added to the database perfectly so why doesn't the delete work? It's as if the items that are removed are not marked for delete.

Is there something that i am doing wrong? or is there something that i have missed? I added AllowDelete=true to the CustomerOrdersCollection but still has no effect of the deleting of the items.

Thanks very much for your help.

Otis avatar
Otis
LLBLGen Pro Team
Posts: 39872
Joined: 17-Aug-2003
# Posted on: 07-Nov-2006 11:07:16   

Is there some kind of 'save' button on that grid? As the datasourcecontrol hasn't got a call from the grid to do anything otherwise the entities would have been deleted from the db. In devexpress' ASPxGrid for example you can delete rows as well and nothing happens till you click the Save button on the grid which performs the actual call to the datasourcecontrol.

I don't know the r.a.d. grid though it should work as the vanilla .net grid works as well.

Frans Bouma | Lead developer LLBLGen Pro
deathwish
User
Posts: 56
Joined: 07-Nov-2006
# Posted on: 07-Nov-2006 11:27:57   

No there is no 'save' button.

I am adding/removing items directly, i assume in the viewstate, from the entitycollection of the entity returned by the llblgenprodatasource, not from the database.

Here is some code for the add button:

Data.EntityClasses.StationEntity station = stationCollectionDataSource.EntityCollection[0] as Data.EntityClasses.StationEntity;

Data.EntityClasses.SiteStationEntity siteStation = station.SiteStation.AddNew(); siteStation.StationId = station.StationId; siteStation.SiteId = siteEntity.SiteId;

Note: stationCollectionDataSource is a llblgenprodatasouce on the page and it is set as the datasourceid for the detailsview.

Here is some code for the remove button:

Data.EntityClasses.StationEntity station = stationCollectionDataSource.EntityCollection[0] as Data.EntityClasses.StationEntity; station.SiteStation.AllowRemove = true; station.SiteStation.Remove(station.SiteStation[0]);

Then when you click "Update" on the detailsview, the entitycollection for the entity should be saved to the database. There is no other saving going on in the page.

How come the items that were added to the stationCollectionDataSource, are inserted into the database, but items that were removed from the stationCollectionDataSource are not deleted from the database?

Thanks very much.

deathwish
User
Posts: 56
Joined: 07-Nov-2006
# Posted on: 07-Nov-2006 13:29:50   

Hi,

The r.a.d grid is bound to the EntityCollection (which is a SiteStationCollection) of the StationEntity (from the datasroucecontrol) that is bound to the detailsview. There is only one llblgenprodatasource control on the page.

So how do i tell the datasourcecontrol to update the SiteStationCollection of the StationEntity in the datasourcecontrol?

No SQL is fired for removing the SiteStationCollection items but the item has been removed from the SiteStationCollection of the StationEntity in the datasourcecontrol. I checked by debugging the detailsview itemupdated command and running sql profiler.

SQL is fired for adding items to the SiteStationCollection items so something is telling the datasource control to update the SiteStationCollection of the StationEntity in the datasourcecontrol.

Thanks.

Otis avatar
Otis
LLBLGen Pro Team
Posts: 39872
Joined: 17-Aug-2003
# Posted on: 08-Nov-2006 09:31:35   

When you remove an entity from a collection, and then save the collection, the entity isn't deleted from the database. This is done for a reason: removing an entity from a collection can also mean, you just want to remove the entity from the collection. So deletes are explicit: you've to specify what to delete.

When I bind a gridview to an llblgenprodatasource control and delete a line, the entity IS deleted because the gridview calls the datasource control's ExecuteDelete method, which is the standard method to get things deleted with datasourcecontrols and thus also with LLBLGenProDataSource(2) controls.

But I think what's happening is (if I understand your posts correctly) that you bind the entitycollection to the grid and not the datasourcecontrol. You should bind a datasourcecontrol to the grid. then the deletes are correctly handled for you.

Rule of thumb: 2-way databinding in webforms: use datasourcecontrols, ALWAYS. Otherwise, you've to perform the actions manually, and thus in case of deletes: track which entities are removed from an entitycollection and then delete them yourself.

Frans Bouma | Lead developer LLBLGen Pro
deathwish
User
Posts: 56
Joined: 07-Nov-2006
# Posted on: 08-Nov-2006 12:56:27   

Hi Otis,

Thanks very much for the help. it's becomming clear to me now.

I have posted a picture on showing the page that i am trying to create.

If you could give as a rough idea of the architecture for the page so that we only have to click "Update" to save the details in the detailsview and the items that were added/removed to the bottom grid. If the user clicks cancel, nothing must be saved, including the items in the bottom grid.

THere is a datasourcecontrol that the detailsview is bound to which is a StationEntity. and then in code i was binding the bottom grid to datasourceontrol.EntityCollection[0].EntityCollection. The add button adds items to the datasourceontrol.EntityCollection[0].EntityCollection.Add() and the remove is supposed to be datasourceontrol.EntityCollection[0].EntityCollection.Remove().

Thanks very much for the great support.

Walaa avatar
Walaa
Support Team
Posts: 14994
Joined: 21-Aug-2005
# Posted on: 08-Nov-2006 15:50:46   

The Remove button should add the removed Items into some other Collection. And when you perform the Update action, you should delete those entities as well from the database.

Try to set the llblgenprodatasource's LivePersistence = false, so you can handle the actions yourself. Please refer to the LLBLGen Pro manual: "Using the generated code -> SelfServicing -> Databinding at design time and runtime -> Databinding with ASP.NET 2.0"

Check the LivePersistence and events section.

There you can use the UnitOfWork object to add a collection for delete (The some other collection we created for the removed entities).

deathwish
User
Posts: 56
Joined: 07-Nov-2006
# Posted on: 08-Nov-2006 15:57:36   

Hi,

Thanks very much for the help.

Russell.

deathwish
User
Posts: 56
Joined: 07-Nov-2006
# Posted on: 09-Nov-2006 15:44:27   

Hey, it's me again. Ur worsst nightmare....

Ok so the LivePersistence="false", PerformSelect, PerformWork and PerformGetDBCount are all being used.

It seems to be working fine. When editing a station, everything works perfectly, it is updated correctly. The SiteStationCollection for the Station is also saved correctly in the PerformWork function, using:

e.Uow.AddCollectionForSave(stationEntity.SiteStation, false); e.Uow.AddCollectionForDelete(RemovedSiteStationCollection);

When an item is being inserted, it is already in the e.UoW from the detailsview, how do i add items to the SiteStationCollection for that new entity in the _entitiesToSave. It does not link the Station to the SiteStationCollection items when the Station is inserted (the StationId needs to be set on the SiteStationCollection items) so the SiteStationCollection is not saved.

Thanks very much.

deathwish
User
Posts: 56
Joined: 07-Nov-2006
# Posted on: 09-Nov-2006 21:16:56   

Hey guys,

here is my code for that page i posted in the screenshot.


<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="StationListControl.ascx.cs" Inherits="preLink.Web.UI.UserControl.Admin.Site.Station.StationListControl" %>
<%@ register assembly="RadGrid.Net2" namespace="Telerik.WebControls" tagprefix="radG" %>
<%@ register assembly="RadTabStrip.Net2" namespace="Telerik.WebControls" tagprefix="radTS" %>
<%@ register assembly="SD.LLBLGen.Pro.ORMSupportClasses.NET20" namespace="SD.LLBLGen.Pro.ORMSupportClasses" tagprefix="llblgenpro" %>
<%@ register assembly="preLink.Web.UI" namespace="preLink.Web.UI.CustomControl" tagprefix="preLink" %>
<%@ register assembly="RadAjax.Net2" namespace="Telerik.WebControls" tagprefix="radA" %>

<llblgenpro:llblgenprodatasource id="stationCollectionDataSource" runat="server" datacontainertype="EntityCollection" 
    entitycollectiontypename="preLink.Data.CollectionClasses.StationCollection, preLink.Data" enablepaging="true" livepersistence="false" 
    onperformgetdbcount="stationCollectionDataSource_PerformGetDbCount" onperformselect="stationCollectionDataSource_PerformSelect" 
    onperformwork="stationCollectionDataSource_PerformWork">
</llblgenpro:llblgenprodatasource>

<rada:radajaxpanel id="radAjaxPanel" runat="server" height="200px" width="100%" onload="Page_Load">
    <radTS:RadMultiPage id="radMultiPage" Runat="server" selectedindex="0">
        <radTS:PageView id="pvStationList" runat="server">
            <prelink:prelinkradgrid id="stationRadGrid" runat="server"
                datasourceid="stationCollectionDataSource" radmultipageid="radMultiPage" prelinkdetailsviewid="dvStation" autogeneratecolumns="False">
                <mastertableview datakeynames="StationId" datasourceid="stationCollectionDataSource" commanditemdisplay="TopAndBottom">
                    <expandcollapsecolumn filterimageurl="" sortascimageurl="" sortdescimageurl="" visible="False">
                        <headerstyle width="19px" />
                    </expandcollapsecolumn>
                    <rowindicatorcolumn visible="False">
                        <headerstyle width="20px" />
                    </rowindicatorcolumn>
                    <columns>
                        <radg:gridboundcolumn datafield="Name" headertext="Name" sortexpression="Name" uniquename="Name">
                        </radg:gridboundcolumn>
                        <radg:gridboundcolumn datafield="SiteName" headertext="Site Name" sortexpression="SiteName"
                            uniquename="SiteName">
                        </radg:gridboundcolumn>
                        <radg:gridboundcolumn datafield="SiteCode" headertext="Site Code" sortexpression="SiteCode"
                            uniquename="SiteCode">
                        </radg:gridboundcolumn>
                        <radg:gridtemplatecolumn uniquename="EditColumn" itemstyle-horizontalalign="center">
                            <itemtemplate>
                                <asp:linkbutton id="Linkbutton1" runat="server" causesvalidation="false" commandname="Edit" text="Edit"></asp:linkbutton>
                            </itemtemplate>
                        </radg:gridtemplatecolumn>
                        <radg:gridtemplatecolumn uniquename="DeleteColumn" itemstyle-horizontalalign="center">
                            <itemtemplate>
                                <asp:linkbutton id="Delete" runat="server" causesvalidation="false" commandname="Delete"
                                    text="Delete">
                                </asp:linkbutton>                           
                            </itemtemplate>
                        </radg:gridtemplatecolumn>
                    </columns>                  
                    <editformsettings>
                        <editcolumn filterimageurl="" sortascimageurl="" sortdescimageurl="">
                        </editcolumn>
                    </editformsettings>
                </mastertableview>
                <pagerstyle mode="NextPrevAndNumeric" position="TopAndBottom" />
                <clientsettings allowcolumnsreorder="True" allowdragtogroup="True" reordercolumnsonclient="True">
                </clientsettings>
            </prelink:prelinkradgrid>       
        </radTS:PageView>
        <radts:pageview id="pvStation" runat="server">
            <llblgenpro:llblgenprodatasource id="sitesCollectionDataSource" runat="server" datacontainertype="EntityCollection" 
                entitycollectiontypename="preLink.Data.CollectionClasses.SiteCollection, preLink.Data">
            </llblgenpro:llblgenprodatasource>

            <llblgenpro:llblgenprodatasource id="printerCollectionDataSource" runat="server" datacontainertype="EntityCollection" 
                entitycollectiontypename="preLink.Data.CollectionClasses.PrinterCollection, preLink.Data">
            </llblgenpro:llblgenprodatasource>

            <llblgenpro:llblgenprodatasource id="priorityCollectionDataSource" runat="server" datacontainertype="EntityCollection" 
                entitycollectiontypename="preLink.Data.CollectionClasses.PriorityCollection, preLink.Data">
            </llblgenpro:llblgenprodatasource>
            
            <llblgenpro:llblgenprodatasource id="stationTypeCollectionDataSource" runat="server" datacontainertype="EntityCollection" 
                entitycollectiontypename="preLink.Data.CollectionClasses.StationTypeCollection, preLink.Data">
            </llblgenpro:llblgenprodatasource>

            <prelink:prelinkdetailsview id="dvStation" runat="server" autogeneraterows="False" cssclass="detailsview"
                    datakeynames="StationId" datasourceid="stationCollectionDataSource" gridlines="none"
                    prelinkradgridid="stationRadGrid" radmultipageid="radMultiPage">
                <fieldheaderstyle cssclass="fieldheaderstyle" />
                <headertemplate>
                    <asp:validationsummary id="valSummary" runat="server" headertext="Validation Errors:" />
                    <b>Station Details</b>
                </headertemplate>
                <fields>
                    <asp:templatefield headertext="Site:">
                        <itemtemplate>
                            <asp:dropdownlist id="ddlSite" runat="server" datasourceid="sitesCollectionDataSource" appenddatabounditems="true"
                                datavaluefield="SiteId" datatextfield="Name" selectedvalue='<%# Bind("SiteId") %>'>
                                <asp:listitem text="-- Select One --" value=""></asp:listitem>
                            </asp:dropdownlist>
                            <asp:requiredfieldvalidator id="valSite" runat="server" errormessage="Site is required" controltovalidate="ddlSite">*</asp:requiredfieldvalidator>
                        </itemtemplate>
                    </asp:templatefield>
                    <asp:templatefield headertext="Station Type:">
                        <itemtemplate>
                            <asp:dropdownlist id="ddlStationType" runat="server" datasourceid="stationTypeCollectionDataSource" autopostback="true" selectedvalue='<%# Bind("StationTypeId") %>' datatextfield="Name" datavaluefield="StationTypeId" appenddatabounditems="true" 
                                OnSelectedIndexChanged="ddlStationType_SelectedIndexChanged" OnDataBinding="ddlStationType_DataBinding"> 
                                <asp:listitem text="-- Select One --" value=""></asp:listitem>
                            </asp:dropdownlist>
                            <asp:requiredfieldvalidator id="valStationType" runat="server" controltovalidate="ddlStationType" errormessage="Station Type is required">*</asp:requiredfieldvalidator>                        
                        </itemtemplate>
                    </asp:templatefield>
                    <asp:templatefield headertext="Name:">
                        <itemtemplate>
                            <asp:textbox id="txtName" runat="server" text='<%# Bind("Name") %>' cssclass="textbox"></asp:textbox>
                            <asp:requiredfieldvalidator id="valName" runat="server" controltovalidate="txtName" errormessage="Station Name is required">*</asp:requiredfieldvalidator>                      
                        </itemtemplate>
                    </asp:templatefield>
                    <asp:templatefield headertext="Description:">
                        <itemtemplate>
                            <asp:textbox id="txtDescription" runat="server" text='<%# Bind("Description") %>' cssclass="textbox"></asp:textbox>
                        </itemtemplate>
                    </asp:templatefield>
                    <asp:templatefield headertext="Pass Code:">
                        <itemtemplate>
                            <asp:textbox id="txtPassCode" runat="server" text='<%# Bind("PassCode") %>' cssclass="textbox"></asp:textbox>
                        </itemtemplate>
                    </asp:templatefield>
                    <asp:templatefield headertext="Show Host:">
                        <itemtemplate>
                            <asp:checkbox id="chkShowHost" runat="server" checked='<%# Bind("ShowHost") %>' />
                        </itemtemplate>
                    </asp:templatefield>                    
                    <asp:templatefield headertext="Import:">
                        <itemtemplate>
                            <asp:checkbox id="chkImport" runat="server" autopostback="true" checked='<%# Bind("Import") %>' OnCheckedChanged="chkImport_CheckedChanged"
                                OnDataBinding="chkImport_DataBinding"></asp:checkbox> 
                        </itemtemplate>
                    </asp:templatefield>
                    <asp:templatefield headertext="Server:">
                        <itemtemplate>
                            <asp:textbox id="txtServer" runat="server" text='<%# Bind("Server") %>' cssclass="textbox"></asp:textbox>
                        </itemtemplate>
                    </asp:templatefield>
                    <asp:templatefield headertext="Username:">
                        <itemtemplate>
                            <asp:textbox id="txtUsername" runat="server" text='<%# Bind("Username") %>' cssclass="textbox"></asp:textbox>
                        </itemtemplate>
                    </asp:templatefield>
                    <asp:templatefield headertext="Password:">
                        <itemtemplate>
                            <asp:textbox id="txtPassword" runat="server" text='<%# Bind("Password") %>' cssclass="textbox"></asp:textbox>   
                        </itemtemplate>
                    </asp:templatefield>
                    <asp:templatefield headertext="Address:">
                        <itemtemplate>
                            <asp:textbox id="txtAddress" runat="server" text='<%# Bind("Address") %>' cssclass="textbox"></asp:textbox> 
                        </itemtemplate>
                    </asp:templatefield>
                    <asp:templatefield headertext="Collect Other:">
                        <itemtemplate>
                            <asp:checkbox id="chkCollectOther" runat="server" checked='<%# Bind("CollectOther") %>' />  
                        </itemtemplate> 
                    </asp:templatefield>
                    <asp:templatefield headertext="Default Priority:">
                        <itemtemplate>
                            <asp:dropdownlist id="ddlPriority" runat="server" datasourceid="priorityCollectionDataSource" appenddatabounditems="true"
                                datavaluefield="PriorityId" datatextfield="Name" selectedvalue='<%# Bind("PriorityId") %>'>
                                <asp:listitem text="-- Select Priority --" value=""></asp:listitem>
                            </asp:dropdownlist> 
                        </itemtemplate>
                    </asp:templatefield>                    
                    <asp:templatefield headertext="Print On Receipt:">
                        <itemtemplate>                          
                            <asp:checkbox id="chkPrintOnReceipt" runat="server" checked='<%# Bind("PrintOnReceipt") %>' OnCheckedChanged="chkPrintOnReceipt_CheckedChanged" 
                                autopostback="true" OnDataBinding="chkPrintOnReceipt_DataBinding"></asp:checkbox> 
                        </itemtemplate>
                    </asp:templatefield>
                    <asp:templatefield headertext="Printer:">
                        <itemtemplate>
                            <asp:dropdownlist id="ddlPrinter" runat="server" datasourceid="printerCollectionDataSource" appenddatabounditems="true"
                                datavaluefield="PrinterId" datatextfield="Name" selectedvalue='<%# Bind("PrinterId") %>'>
                                <asp:listitem text="-- Select Printer --" value=""></asp:listitem>
                            </asp:dropdownlist>
                        </itemtemplate>
                    </asp:templatefield>
                    <asp:templatefield></asp:templatefield>
                    <asp:commandfield buttontype="Button" showdeletebutton="True" showeditbutton="True" showinsertbutton="True" />
                </fields>
            </prelink:prelinkdetailsview>

            <div id="divStationController" runat="server" style="float:left; margin-left:20px;" visible="false">
                <llblgenpro:llblgenprodatasource id="siteStationAvailableCollectionDataSource" runat="server" datacontainertype="EntityCollection" 
                    entitycollectiontypename="preLink.Data.CollectionClasses.SiteCollection, preLink.Data" enablepaging="true">
                </llblgenpro:llblgenprodatasource>
                
                <p><b>Station Communication Controller</b></p>
                <p>Select which Laboratories will be controlled by this Station's Communication Controller</p>
                <p>&nbsp;</p>

                <p><b>Available Sites:</b></p>
                <radg:radgrid id="availableRadGrid" runat="server" allowpaging="false" allowsorting="false" enableviewstate="false"
                    datasourceid="siteStationAvailableCollectionDataSource" enableajax="true" horizontalalign="NotSet" height="225px" width="500px">                                        
                    <clientsettings>
                        <scrolling allowscroll="True" usestaticheaders="true" scrollheight="200px" />
                    </clientsettings>
                    <MasterTableView autogeneratecolumns="False" datakeynames="SiteId" datasourceid="siteStationAvailableCollectionDataSource"  >                   
                        <columns>               
                            <radG:GridTemplateColumn UniqueName="TemplateColumn">
                                <HeaderStyle Width="20px"></HeaderStyle>
                                <ItemStyle HorizontalAlign="Center"></ItemStyle>
                                <ItemTemplate>
                                    <asp:CheckBox ID="chkAvailable" AutoPostBack="False" runat="server"></asp:CheckBox>
                                </ItemTemplate>
                            </radG:GridTemplateColumn>
                            <radg:gridboundcolumn datafield="Name" headertext="Site Name" sortexpression="Name" uniquename="Name">
                            </radg:gridboundcolumn>                         
                            <radg:gridboundcolumn datafield="SiteCode" headertext="Site Code" sortexpression="SiteCode" uniquename="SiteCode">
                            </radg:gridboundcolumn>                         
                        </columns>
                    </MasterTableView>
                </radg:radgrid>

                <p style="clear:left;margin-top:10px;">&nbsp;</p>               
                <p style="clear:left; width:500px; text-align:center;">
                    <asp:button id="btnAddSites" runat="server" text="Add" onclick="btnAddSites_Click" causesvalidation="false" />
                    <asp:button id="btnRemoveSites" runat="server" text="Remove" onclick="btnRemoveSites_Click" causesvalidation="false" />
                </p>
                
                <p><b>Sites Controlled by this Station:</b></p>
                <radg:radgrid id="controlledRadGrid" runat="server" allowpaging="false" allowsorting="false" enableviewstate="true"
                    enableajax="true" horizontalalign="NotSet" height="225px" width="500px">                                        
                    <clientsettings>
                        <scrolling allowscroll="True" usestaticheaders="true" scrollheight="200px"/>
                    </clientsettings>
                    <MasterTableView autogeneratecolumns="False" datakeynames="SiteId">                 
                        <columns>
                            <radG:GridTemplateColumn UniqueName="TemplateColumn">
                                <HeaderStyle Width="20px"></HeaderStyle>
                                <ItemStyle HorizontalAlign="Center"></ItemStyle>
                                <ItemTemplate>
                                    <asp:CheckBox ID="chkControlled" AutoPostBack="False" runat="server"></asp:CheckBox>
                                </ItemTemplate>
                            </radG:GridTemplateColumn>
                            <radg:gridboundcolumn datafield="SiteName" headertext="Site Name" sortexpression="Name" uniquename="Name">
                            </radg:gridboundcolumn>                         
                            <radg:gridboundcolumn datafield="SiteCode" headertext="Site Code" sortexpression="SiteCode" uniquename="SiteCode">
                            </radg:gridboundcolumn>                             
                        </columns>
                    </MasterTableView>
                </radg:radgrid>
            </div>          
        </radts:pageview>
    </radTS:RadMultiPage>
</rada:radajaxpanel>

Code Behind:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
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 Telerik.WebControls;
using System.Collections.Generic;
using SD.LLBLGen.Pro.ORMSupportClasses;
using preLink.Data.HelperClasses;

namespace preLink.Web.UI.UserControl.Admin.Site.Station
{
    public partial class StationListControl : System.Web.UI.UserControl
    {
        #region Properties
        /// <summary>
        /// Store the list of items to be removed from the collection when updating
        /// </summary>
        public Data.CollectionClasses.SiteStationCollection RemovedSiteStationCollection
        {
            get
            {
                if (ViewState["_siteStationCollection"] == null)
                    ViewState["_siteStationCollection"] = new Data.CollectionClasses.SiteStationCollection();

                return ViewState["_siteStationCollection"] as Data.CollectionClasses.SiteStationCollection;
            }
            set
            {
                ViewState["_siteStationCollection"] = value;
            }
        }
        #endregion

        protected override void OnInit(EventArgs e)
        {
            this.dvStation.BindData += new preLink.Web.UI.CustomControl.preLinkDetailsView.DataBoundEventHandler(dvStation_BindData);
            base.OnInit(e);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                stationTypeCollectionDataSource.SorterToUse = new SortExpression(StationTypeFields.Metric | SortOperator.Ascending);
                stationCollectionDataSource.SorterToUse = new SortExpression(StationFields.Name | SortOperator.Ascending);
                sitesCollectionDataSource.SorterToUse = new SortExpression(SiteFields.Name | SortOperator.Ascending);
                priorityCollectionDataSource.SorterToUse = new SortExpression(PriorityFields.Metric | SortOperator.Ascending);
            }
        }

        #region DataBind function
        /// <summary>
        /// Bind the station controller grids when the preLinkDetailsView is Bound
        /// </summary>
        /// <param name="sender">Sender</param>
        /// <param name="e">EventArgs</param>
        /// <remarks>Russell Olivier</remarks>
        protected void dvStation_BindData(object sender, EventArgs e)
        {
            // Russell Olivier - 08/11/2006: Get the station
            Data.EntityClasses.StationEntity stationEntity = stationCollectionDataSource.EntityCollection[0] as Data.EntityClasses.StationEntity;
            RemovedSiteStationCollection = new preLink.Data.CollectionClasses.SiteStationCollection();
            
            // Russell Olivier: Set the sort order of the datasources
            siteStationAvailableCollectionDataSource.SorterToUse = new SortExpression(SiteFields.Name | SortOperator.Ascending);

            // Russell Olivier - 08/11/2006: Create a filter 
            PredicateExpression availablePredicate = new PredicateExpression();         

            // Russell Olivier - 08/11/2006: Check if the detailsview 
            if (dvStation.CurrentMode == DetailsViewMode.Edit)
            {
                // Russell Olivier - 08/11/2006: Set the filter to get a list of all the sites not controlled by the  selected station
                availablePredicate.Add(new FieldCompareSetPredicate(SiteFields.SiteId, SiteStationFields.SiteId, SetOperator.In, (SiteStationFields.StationId == stationEntity.StationId)));
                availablePredicate.Negate = true;
            }
            else
                stationEntity.SiteStation.Clear();

            // Russell Olivier - 08/11/2006: Set the new filter
            siteStationAvailableCollectionDataSource.FilterToUse = availablePredicate;

            // Russell Olivier - 08/11/2006: Bind the Sites that are controlled by this station
            stationEntity.SiteStation.AllowRemove = true;
            controlledRadGrid.DataSource = stationEntity.SiteStation;
            controlledRadGrid.DataBind();
            
            // Russell Olivier - 08/11/2006: Hide or show the station controller section.
            if (stationEntity.StationTypeId == Data.EntityClasses.StationTypeEntity.preLinkControl && dvStation.CurrentMode == DetailsViewMode.Edit)
                divStationController.Visible = true;
            else
                divStationController.Visible = false;
        }
        #endregion

        #region Button Events
        /// <summary>
        /// Move the sites from the available radgrid to the controlled radgrid
        /// </summary>
        /// <param name="sender">Sender</param>
        /// <param name="e">EventArgs</param>
        /// <remarks>Russell Olivier</remarks>
        protected void btnAddSites_Click(object sender, EventArgs e)
        {           
            // Russell Olivier: Get the station
            Data.EntityClasses.StationEntity stationEntity = stationCollectionDataSource.EntityCollection[0] as Data.EntityClasses.StationEntity;

            foreach (GridDataItem item in availableRadGrid.MasterTableView.Items)
            {
                CheckBox chkAvailable = item.FindControl("chkAvailable") as CheckBox;

                if (chkAvailable == null)
                    continue;

                if (chkAvailable.Checked)
                {
                    string siteId = item.OwnerTableView.DataKeyValues[item.ItemIndex]["SiteId"].ToString();
                    // Russell Olivier: Get the SiteEntity index
                    List<int> foundEntities = siteStationAvailableCollectionDataSource.EntityCollection.FindMatches(
                        new PredicateExpression(new FieldCompareValuePredicate(SiteFields.SiteId, ComparisonOperator.Equal, siteId)));

                    // Russell Olivier: Get the SiteEntity
                    Data.EntityClasses.SiteEntity siteEntity = siteStationAvailableCollectionDataSource.EntityCollection[foundEntities[0]] as Data.EntityClasses.SiteEntity;

                    // Russell Olivier: Add the SiteStation to the collection
                    Data.EntityClasses.SiteStationEntity siteStationEntity = new Data.EntityClasses.SiteStationEntity();
                    siteStationEntity.StationId = stationEntity.StationId;
                    siteStationEntity.SiteId = siteEntity.SiteId;
                    stationEntity.SiteStation.Add(siteStationEntity);

                    RemovedSiteStationCollection.Remove(siteStationEntity);
                    // Russell Olivier: Remove the siteEntity from the Available collection
                    siteStationAvailableCollectionDataSource.EntityCollection.Remove(siteEntity);
                }
            }

            controlledRadGrid.DataSource = stationEntity.SiteStation;
            controlledRadGrid.DataBind();
            availableRadGrid.Rebind();
        }

        /// <summary>
        /// Move the sites from the controlled radgrid to the available radgrid
        /// </summary>
        /// <param name="sender">Sender</param>
        /// <param name="e">EventArgs</param>
        /// <remarks>Russell Olivier</remarks>
        protected void btnRemoveSites_Click(object sender, EventArgs e)
        {           
            // Russell Olivier: Get the station
            Data.EntityClasses.StationEntity stationEntity = stationCollectionDataSource.EntityCollection[0] as Data.EntityClasses.StationEntity;
            
            foreach (GridDataItem item in controlledRadGrid.MasterTableView.Items)
            {
                CheckBox chkAvailable = item.FindControl("chkControlled") as CheckBox;

                if (chkAvailable == null)
                    continue;

                if (chkAvailable.Checked)
                {
                    string siteId = item.OwnerTableView.DataKeyValues[item.ItemIndex]["SiteId"].ToString();
                    // Russell Olivier: Get the SiteEntity index
                    List<int> foundEntities = stationEntity.SiteStation.FindMatches(
                        new PredicateExpression(new FieldCompareValuePredicate(SiteStationFields.SiteId, ComparisonOperator.Equal, siteId)));

                    // Russell Olivier: Get the SiteEntity
                    Data.EntityClasses.SiteEntity siteEntity = stationEntity.SiteStation[foundEntities[0]].Site;
                    // Russell Olivier: Add the siteEntity to the Available collection
                    siteStationAvailableCollectionDataSource.EntityCollection.Add(siteEntity);

                    RemovedSiteStationCollection.Add(stationEntity.SiteStation[foundEntities[0]]);
                    // Russell Olivier: Remove the siteStation entity                   
                    stationEntity.SiteStation.Remove(stationEntity.SiteStation[foundEntities[0]]);
                }
            }

            controlledRadGrid.DataSource = stationEntity.SiteStation;
            controlledRadGrid.DataBind();
            availableRadGrid.Rebind();
        }
        #endregion

        #region DropDownList Events
        /// <summary>
        /// Called when the stationtype dropdown has changed
        /// </summary>
        /// <param name="sender">Sender</param>
        /// <param name="e">EventArgs</param>
        /// <remarks>Russell Olivier</remarks>
        protected void ddlStationType_SelectedIndexChanged(object sender, EventArgs e)
        {
            DropDownList ddl = sender as DropDownList;
            BindStationTypeControls(ddl);           
        }

        /// <summary>
        /// Hide or show the station controller panel depending on the selectedvalue
        /// </summary>
        /// <param name="ddl">DropDownList that has called the function</param>
        /// <remarks>Russell Olivier</remarks>
        private void BindStationTypeControls(DropDownList ddl)
        {
            // Russell Olivier - 2006/11/08 : Hide the station controller section if the station is not a preLink Control
            if (Utilities.CustomConvert.ToGuid(ddl.SelectedValue) == Data.EntityClasses.StationTypeEntity.preLinkControl)
                divStationController.Visible = true;
            else
                divStationController.Visible = false;
        }

        /// <summary>
        /// Called when the StationType DropDownList is bound
        /// </summary>
        /// <param name="sender">The calling dropdownlist</param>
        /// <param name="e">The EventArgs of the call</param>
        /// <remarks>Russell Olivier</remarks>
        protected void ddlStationType_DataBinding(object sender, EventArgs e)
        {
            DropDownList ddl = sender as DropDownList;
            BindStationTypeControls(ddl);
        }
        #endregion

        #region DataSource Events
        /// <summary>
        /// Get the DBCount used for paging when enablepaging=true
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <remarks>Russell Olivier</remarks>
        protected void stationCollectionDataSource_PerformGetDbCount(object sender, PerformGetDbCountEventArgs e)
        {
            e.DbCount = e.ContainedCollection.GetDbCount(e.Filter);         
        }

        /// <summary>
        /// Get the items from the database
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <remarks>Russell Olivier</remarks>
        protected void stationCollectionDataSource_PerformSelect(object sender, PerformSelectEventArgs e)
        {           
            e.ContainedCollection.GetMulti(e.Filter, e.PageSize, e.Sorter, e.Relations, e.PrefetchPath, e.PageNumber, e.PageSize);
        }

        /// <summary>
        /// Insert/Update/Delete the entitycollection to the database
        /// </summary>
        /// <param name="sender">The Calling object</param>
        /// <param name="e">The PerformWorkEventArgs of the calling object</param>
        /// <remarks>Russell Olivier</remarks>
        protected void stationCollectionDataSource_PerformWork(object sender, PerformWorkEventArgs e)
        {
            Data.EntityClasses.StationEntity stationEntity = stationCollectionDataSource.EntityCollection[0] as Data.EntityClasses.StationEntity;
            Guid stationId = Guid.NewGuid();

            // Russell Olivier: Check if the station controller section is visible
            if (divStationController.Visible)
            {
                if (!stationEntity.IsNew)               
                    // Russell Olivier: Remove the items from the siteStation entity collection
                    e.Uow.AddCollectionForDelete(RemovedSiteStationCollection);

                // Russell Olivier: Save the SiteStation entity collection items
                e.Uow.AddCollectionForSave(stationEntity.SiteStation, false);
            }
            else
                e.Uow.AddCollectionForDelete(stationEntity.GetMultiSiteStation(true));

            // Russell Olivier: Save the station entity
            e.Uow.Commit(new Transaction(IsolationLevel.ReadCommitted, "UOW"), true);
        }
        #endregion

        #region CheckBox Events
        /// <summary>
        /// Called when the Print checkbox is clicked
        /// </summary>
        /// <param name="sender">The calling checkbox</param>
        /// <param name="e">The EventArgs for the call</param>
        /// <remarks>Russell Olivier</remarks>
        protected void chkPrintOnReceipt_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox chk = sender as CheckBox;
            BindPrinterControls(chk);
        }

        /// <summary>
        /// Called when the Print checkbox is bound
        /// </summary>
        /// <param name="sender">The calling checkbox</param>
        /// <param name="e">The EventArgs for the call</param>
        /// <remarks>Russell Olivier</remarks>
        protected void chkPrintOnReceipt_DataBinding(object sender, EventArgs e)
        {
            CheckBox chk = sender as CheckBox;
            BindPrinterControls(chk);
        }

        /// <summary>
        /// Hide or show the Printer dropdownlist
        /// </summary>
        /// <param name="chk"></param>
        /// <remarks>Russell Olivier</remarks>
        private void BindPrinterControls(CheckBox chk)
        {
            dvStation.Rows[14].Visible = chk.Checked;
        }   

        /// <summary>
        /// Called when the import checkbox is clicked
        /// </summary>
        /// <param name="sender">The calling checkbox</param>
        /// <param name="e">The EventArgs for the call</param>
        /// <remarks>Russell Olivier</remarks>
        protected void chkImport_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox chk = sender as CheckBox;
            DisplayImportControls(chk);         
        }

        /// <summary>
        /// Called when the import checkbox is bound
        /// </summary>
        /// <param name="sender">The calling checkbox</param>
        /// <param name="e">The EventArgs for the call</param>
        /// <remarks>Russell Olivier</remarks>
        protected void chkImport_DataBinding(object sender, EventArgs e)
        {
            CheckBox chk = sender as CheckBox;
            DisplayImportControls(chk);
        }

        /// <summary>
        /// Hide or show the Import details fields
        /// </summary>
        /// <param name="chk">The checkbox that was checked</param>
        /// <remarks>Russell Olivier</remarks>
        private void DisplayImportControls(CheckBox chk)
        {
            dvStation.Rows[7].Visible = chk.Checked;
            dvStation.Rows[8].Visible = chk.Checked;
            dvStation.Rows[9].Visible = chk.Checked;
            dvStation.Rows[10].Visible = chk.Checked;
        }
        #endregion
    }
}


Is there anyway to do what i am trying to do without using LivePersistence="false", use LivePersistence="true" so that the datasource will update the Station and the Station.SiteStation? So i don't need to code the performselect, PerformWork and PerformGetDbCount methods.

One more thing. When u create a new entity, does it populate the PK fields with a value? I have used CSLA before and when u create a new Data.EntityClasses.Station(), for example, the StationId will have a value. If it were a Guid for example.

Thanks.

Otis avatar
Otis
LLBLGen Pro Team
Posts: 39872
Joined: 17-Aug-2003
# Posted on: 09-Nov-2006 21:36:38   

Could you please cut that post up to the pieces which matter? That's a lot of code, and I don't think it's relevant in full. What matters is that ALL actions should be done ON the grid: deletes, inserts, updates etc. The grid then calls the datasourcecontrol to update the data, which will result in the raise of the PerformWork event, to which you bind an event handler.

When you do maintenance on the collection yourself, i.e. datasourcecontrol.Entitycollection.Add/Remove etc., it won't work, as the grid is working with the same collection but won't get live notifcations of your changes because web is a request - response system: once the grid is rendered, nothing can change that afterwards, even if some code in the page is executed after that rendering.

Frans Bouma | Lead developer LLBLGen Pro
deathwish
User
Posts: 56
Joined: 07-Nov-2006
# Posted on: 09-Nov-2006 22:46:15   

I thought it would all be relevent to explain what i was trying to do. Trying to do what Walaa had explained about doing it manually, i.e. not using LivePersistence.

Ok so if i don't do it manually, how can I use a datasourcecontrol on the grid and one on the detailsview so that when u click save on the detailsview, the datasource on the detailsview and the grid is saved. If changes are made to the grid and the user clicks cancel on the detailsview, the changes to the grid are not persistend to the database.

Thanks.

Walaa avatar
Walaa
Support Team
Posts: 14994
Joined: 21-Aug-2005
# Posted on: 10-Nov-2006 08:11:46   

Since you should handle the Perform work of the detailsview datasource, there you can also access the grid datasource.UnitOfWorkObject and commit it along the way.