EditTemplate combo callback and itemdatabound

3 posts, 1 answers
  1. Yeroon
    Yeroon avatar
    87 posts
    Member since:
    Oct 2012

    Posted 14 Dec 2011 Link to this post

    Hello,

    I have a grid on my page with a GridEditCommandColumn. In the OnItemDataBound of the grid is disable this column for certain gridrows. This works fine. Now when I enter edit mode for one of the items I show in one column a RadCombobox which does an Ajax callback when the selection changes, to fill another depending RadCombobox. This works fine aswell. But the problem is that all rows (including the earlier rows with no edit command) get an Edit command before them. The item being edited stays in edit mode, but just all other rows now also show an edit column/button. I hope the attached screenshots can make more clear what I mean.

    The aspx code:

    <telerik:RadAjaxManager ID="RadAjaxManager1" runat="server">
            <AjaxSettings>
                <telerik:AjaxSetting AjaxControlID="gridResult">
                    <UpdatedControls>
                        <telerik:AjaxUpdatedControl ControlID="gridResult" />
                        <telerik:AjaxUpdatedControl ControlID="lblGewerkt" />
                        <telerik:AjaxUpdatedControl ControlID="lblZiek" />
                        <telerik:AjaxUpdatedControl ControlID="lblMutatie" />
                        <telerik:AjaxUpdatedControl ControlID="txtVakantie" />
                        <telerik:AjaxUpdatedControl ControlID="txtZiek" />
                        <telerik:AjaxUpdatedControl ControlID="txtOveruren" />
                        <telerik:AjaxUpdatedControl ControlID="txtHoursheetsLocal" />
                        <telerik:AjaxUpdatedControl ControlID="rdpDate" />
                    </UpdatedControls>
                </telerik:AjaxSetting>
                <telerik:AjaxSetting AjaxControlID="rdpDate">
                    <UpdatedControls>
                        <telerik:AjaxUpdatedControl ControlID="gridResult" />
                        <telerik:AjaxUpdatedControl ControlID="lblGewerkt" />
                        <telerik:AjaxUpdatedControl ControlID="lblZiek" />
                        <telerik:AjaxUpdatedControl ControlID="lblMutatie" />
                        <telerik:AjaxUpdatedControl ControlID="txtVakantie" />
                        <telerik:AjaxUpdatedControl ControlID="txtZiek" />
                        <telerik:AjaxUpdatedControl ControlID="txtOveruren" />
                        <telerik:AjaxUpdatedControl ControlID="lblWeek" />
                        <telerik:AjaxUpdatedControl ControlID="lblDag" />
                        <telerik:AjaxUpdatedControl ControlID="lblBlocked" />
                    </UpdatedControls>
                </telerik:AjaxSetting>
                <telerik:AjaxSetting AjaxControlID="cmbProjects">
                    <UpdatedControls>
                        <telerik:AjaxUpdatedControl ControlID="gridResult" />
                    </UpdatedControls>
                </telerik:AjaxSetting>
            </AjaxSettings>
        </telerik:RadAjaxManager>
        <!-- /RadAjaxManager -->
        <!-- daysheet !-->
        <table width="100%" class="ShowValueTable">
            <tr>
                <td class="contents">
                    <telerik:RadDatePicker runat="server" ID="rdpDate" DateInput-DateFormat="dd-MM-yyyy"
                        Culture="nl-NL" OnSelectedDateChanged="rdpDate_SelectedDateChanged" Enabled="true">
                        <DatePopupButton runat="server" />
                        <Calendar ID="Calendar1" runat="server" />
                        <DateInput ID="DateInput1" runat="server" AutoPostBack="true" DateFormat="dd-MM-yyyy"
                            DisplayDateFormat="dd-MM-yyyy">
                            <IncrementSettings InterceptMouseWheel="false" />
                        </DateInput>
                    </telerik:RadDatePicker>
                    <asp:Label runat="server" ID="lblWeek" />
                </td>
                <td class="label">
                    Vakantie:
                </td>
                <td class="contents">
                    <asp:LinkButton runat="server" CausesValidation="false" ID="txtVakantie" OnClientClick="openWindowMutation"></asp:LinkButton>
                </td>
                <td class="label">
                    Contract:
                </td>
                <td class="contents">
                    <asp:Label runat="server" ID="lblContract" />
                </td>
            </tr>
            <tr>
                <td class="contents" rowspan="2" style="text-align: center; font-size: 14pt;">
                    <asp:Label runat="server" ID="lblDag" />
                    <asp:Label runat="server" ID="lblBlocked" Font-Size="10pt" Style="color: Red;" />
                </td>
                <td class="label">
                    Ziek:
                </td>
                <td class="contents">
                    <asp:LinkButton runat="server" CausesValidation="false" ID="txtZiek" OnClientClick="openWindowMutation"></asp:LinkButton>
                </td>
                <td class="label">
                    Gewerkt:
                </td>
                <td class="contents">
                    <asp:Label runat="server" ID="lblGewerkt" />
                </td>
            </tr>
            <tr>
                <td class="label">
                    Overuren:
                </td>
                <td class="label">
                    <asp:LinkButton runat="server" CausesValidation="false" ID="txtOveruren" OnClientClick="openWindowMutation"></asp:LinkButton>
                </td>
                <td class="label">
                    Mutatie:
                </td>
                <td class="contents">
                    <asp:Label runat="server" ID="lblMutatie" />
                    <asp:Label runat="server" ID="lblMaxZiek" Style="display: none;" />
                </td>
            </tr>
        </table>
        <!-- /daysheet !-->
     
        <br />
        <br />
     
        <!-- hoursheet !-->
        <telerik:RadGrid runat="server" ID="gridResult" AutoGenerateColumns="False" OnItemDataBound="gridResult_ItemDataBound"
            OnUpdateCommand="gridResult_UpdateCommand" OnDeleteCommand="gridResult_DeleteCommand"
            OnInsertCommand="gridResult_InsertCommand" OnNeedDataSource="gridResult_NeedDataSource"
            OnItemCommand="gridResult_ItemCommand" EnableViewState="true">
            <MasterTableView TableLayout="Fixed" DataKeyNames="OID" EditMode="InPlace" CommandItemDisplay="Top"
                InsertItemDisplay="Bottom" NoMasterRecordsText="Geen taken om weer te geven">
                <CommandItemSettings AddNewRecordText="Nieuwe taak toevoegen" ShowRefreshButton="false" />
                <SortExpressions>
                    <telerik:GridSortExpression FieldName="Starttijd" SortOrder="Ascending" />
                </SortExpressions>
                <Columns>
                    <telerik:GridEditCommandColumn  ButtonType="ImageButton" UniqueName="EditCommandColumn">
                        <ItemStyle CssClass="MyImageButton" VerticalAlign="Top" />
                        <HeaderStyle Width="5%"></HeaderStyle>
                    </telerik:GridEditCommandColumn>
                    <telerik:GridBoundColumn UniqueName="OID" DataField="OID" HeaderText="OID" Visible="false" />
                    <telerik:GridTemplateColumn HeaderText="Starttijd" UniqueName="Starttijd" AllowFiltering="false"
                        HeaderStyle-Width="10%" ItemStyle-VerticalAlign="Top">
                        <ItemTemplate>
                            <asp:Label ID="lblStartTijd" Text='<%# bind("Starttijd") %>' runat="server" />
                        </ItemTemplate>
                        <EditItemTemplate>
                            <telerik:RadMaskedTextBox runat="server" SelectionOnFocus="SelectAll" ID="txtStarttijd"
                                Text='<%# bind("Starttijd") %>' Mask="<0..23>:<0..59>" Width="85%">
                                <ClientEvents OnBlur="BlurStarttijd" OnLoad="InitStarttijd" />
                            </telerik:RadMaskedTextBox>
                        </EditItemTemplate>
                        <InsertItemTemplate>
                            <telerik:RadMaskedTextBox runat="server" SelectionOnFocus="SelectAll" ID="txtStarttijd"
                                Text='<%# bind("TempStartTime") %>' Mask="<0..23>:<0..59>" Width="85%">
                                <ClientEvents OnBlur="BlurStarttijd" OnLoad="InitStarttijd" />
                            </telerik:RadMaskedTextBox>
                        </InsertItemTemplate>
                    </telerik:GridTemplateColumn>
                    <telerik:GridTemplateColumn HeaderText="Eindtijd" UniqueName="Eindtijd" AllowFiltering="false"
                        HeaderStyle-Width="10%" ItemStyle-VerticalAlign="Top">
                        <ItemTemplate>
                            <asp:Label ID="lblEindTijd" Text='<%# bind("Eindtijd") %>' runat="server" />
                        </ItemTemplate>
                        <EditItemTemplate>
                            <telerik:RadMaskedTextBox runat="server" ID="txtEindtijd" Text='<%# bind("Eindtijd") %>'
                                Mask="<0..23>:<0..59>" Width="85%">
                                <ClientEvents OnBlur="BlurEindtijd" OnLoad="InitEindtijd" />
                            </telerik:RadMaskedTextBox>
                            <asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Starttijd mag niet plaatsvinden na eindtijd"
                                Text="*" ClientValidationFunction="compareTime" ControlToValidate="txtEindtijd"
                                SetFocusOnError="true"></asp:CustomValidator>
                            <asp:CustomValidator ID="CustomValidator2" runat="server" ErrorMessage="Er mag geen overlap plaatsvinden tussen een of meerdere ingevoerde taken"
                                Text="*" ClientValidationFunction="checkForOverlap" ControlToValidate="txtEindtijd"
                                SetFocusOnError="true"></asp:CustomValidator>
                        </EditItemTemplate>
                        <InsertItemTemplate>
                            <telerik:RadMaskedTextBox runat="server" ID="txtEindtijd" Text='<%# bind("TempEndTime") %>'
                                Mask="<0..23>:<0..59>" Width="85%">
                                <ClientEvents OnBlur="BlurEindtijd" OnLoad="InitEindtijd" />
                            </telerik:RadMaskedTextBox>
                            <asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Starttijd mag niet plaatsvinden na eindtijd"
                                Text="*" ClientValidationFunction="compareTime" ControlToValidate="txtEindtijd"
                                SetFocusOnError="true"></asp:CustomValidator>
                            <asp:CustomValidator ID="CustomValidator2" runat="server" ErrorMessage="Er mag geen overlap plaatsvinden tussen een of meerdere ingevoerde taken"
                                Text="*" ClientValidationFunction="checkForOverlap" ControlToValidate="txtEindtijd"
                                SetFocusOnError="true"></asp:CustomValidator>
                        </InsertItemTemplate>
                    </telerik:GridTemplateColumn>
                    <telerik:GridDropDownColumn DropDownControlType="RadComboBox"></telerik:GridDropDownColumn>
                    <telerik:GridTemplateColumn HeaderText="Project" UniqueName="Project" AllowFiltering="false"
                        HeaderStyle-Width="25%" ItemStyle-VerticalAlign="Top">
                        <ItemTemplate>
                            <asp:Label ID="lblProject" Text='<%# bind("ProjectNaam") %>' runat="server" />
                        </ItemTemplate>
                         
                        <EditItemTemplate>
                            <telerik:RadComboBox ID="cmbProjects" MarkFirstMatch="true" AllowCustomText="true"
                                DataSource="<%# getProjects() %>" DataTextField="Naam" DataValueField="ProjectNumber"
                                runat="server" SelectedValue='<%# Eval("ProjectID") %>' OnDataBound="cmbProject_Edit_DataBound"
                                OnSelectedIndexChanged="cmbProject_SelectedIndexChanged" OnTextChanged="cmbProject_TextChanged"
                                AutoPostBack="true" CausesValidation="false" Width="75%" />
                            <asp:RequiredFieldValidator ID="ProjectValidator2" runat="server" ControlToValidate="cmbProjects"
                                Text="*" ErrorMessage="Project moet ingevuld worden" SetFocusOnError="true" />
                        </EditItemTemplate>
                        <InsertItemTemplate>
                            <telerik:RadComboBox ID="cmbProjects" MarkFirstMatch="true" AllowCustomText="true"
                                DataSource="<%# getProjects() %>" DataTextField="Naam" DataValueField="ProjectNumber"
                                runat="server" SelectedValue='<%# Eval("ProjectID") %>' OnDataBound="cmbProject_Insert_DataBound"
                                OnSelectedIndexChanged="cmbProject_SelectedIndexChanged" OnTextChanged="cmbProject_TextChanged"
                                AutoPostBack="true" CausesValidation="false" Width="75%" />
                            <asp:RequiredFieldValidator ID="ProjectValidator2" runat="server" ControlToValidate="cmbProjects"
                                Text="*" ErrorMessage="Project moet ingevuld worden" SetFocusOnError="true" />
                        </InsertItemTemplate>
                    </telerik:GridTemplateColumn>
                    <telerik:GridTemplateColumn HeaderText="Deelproject" UniqueName="Project" AllowFiltering="false"
                        HeaderStyle-Width="25%" ItemStyle-VerticalAlign="Top">
                        <ItemTemplate>
                            <asp:Label ID="lblSubProject" Text='<%# bind("SubProjectNaam") %>' runat="server" />
                        </ItemTemplate>
                        <EditItemTemplate>
                            <telerik:RadComboBox ID="cmbSubProjects" MarkFirstMatch="true" AllowCustomText="true"
                                OnTextChanged="cmbSubProject_TextChanged" AutoPostBack="true" CausesValidation="false"
                                runat="server" Width="75%" />
                            <asp:RequiredFieldValidator ID="SubProjectValidator2" runat="server" ControlToValidate="cmbSubProjects"
                                Text="*" ErrorMessage="Subproject moet ingevuld worden" />
                        </EditItemTemplate>
                        <InsertItemTemplate>
                            <telerik:RadComboBox ID="cmbSubProjects" MarkFirstMatch="true" AllowCustomText="true"
                                OnTextChanged="cmbSubProject_TextChanged" AutoPostBack="true" CausesValidation="false"
                                runat="server" Width="75%" />
                            <asp:RequiredFieldValidator ID="SubProjectValidator2" runat="server" ControlToValidate="cmbSubProjects"
                                Text="*" ErrorMessage="Subproject moet ingevuld worden" />
                        </InsertItemTemplate>
                    </telerik:GridTemplateColumn>
                    <telerik:GridTemplateColumn HeaderText="Omschrijving" UniqueName="Omschrijving" AllowFiltering="false"
                        HeaderStyle-Width="20%" ItemStyle-VerticalAlign="Top">
                        <ItemTemplate>
                            <asp:Label ID="lblOmschrijving" Text='<%# bind("Omschrijving") %>' runat="server" />
                        </ItemTemplate>
                        <EditItemTemplate>
                            <telerik:RadTextBox runat="server" ID="txtOmschrijving" Text='<%# bind("Omschrijving") %>'
                                TextMode="MultiLine" Width="80%" SelectionOnFocus="SelectAll" />
                            <asp:RequiredFieldValidator ID="omschrijvingValidator" runat="server" ControlToValidate="txtOmschrijving"
                                Text="*" ErrorMessage="Omschrijving moet ingevuld worden" />
                        </EditItemTemplate>
                    </telerik:GridTemplateColumn>
                    <telerik:GridButtonColumn ButtonType="ImageButton" CommandName="Delete" UniqueName="DeleteCommandColumn"
                        ConfirmDialogType="RadWindow" ConfirmText="Weet u zeker dat u deze taak wilt verwijderen?">
                        <HeaderStyle Width="5%"></HeaderStyle>
                        <ItemStyle CssClass="MyImageButton" VerticalAlign="Top" />
                    </telerik:GridButtonColumn>
                </Columns>
            </MasterTableView>
        </telerik:RadGrid>
        <telerik:GridMaskedColumnEditor ID="GridMaskedColumnEditor1" runat="server" />
        <telerik:GridTextBoxColumnEditor ID="GridTextBoxColumnEditor1" runat="server" TextBoxMode="MultiLine" />
        <telerik:GridDropDownListColumnEditor ID="GridDropDownListColumnEditor1" runat="server" />
        <!-- /hoursheet -->
        <!-- RadWindow -->
        <telerik:RadWindow runat="server" ID="windowMutation" Width="375" Height="375" OnClientClose="windowClose"
            NavigateUrl="AlgemeneUrenInvoer.aspx" Title="Algemene uren bewerken" VisibleStatusbar="false">
        </telerik:RadWindow>
        <!-- /RadWindow -->
        <!-- hidden buttons (used to force save/add) -->
        <asp:Button ID="btnAdd" runat="server" Style="display: none" CausesValidation="false"
            OnClick="AddButton_Click" />
        <asp:Button ID="btnSave" runat="server" Style="display: none" OnClick="SaveButton_Click" />
        <asp:Button ID="btnSubmit" Style="display: none" CausesValidation="true" runat="server" />
        <!-- / hidden buttons -->
        <!-- hidden fields (used for validation) -->
        <asp:TextBox runat="server" ID="txtGewerktMin" Style="display: none"></asp:TextBox>
        <asp:TextBox runat="server" ID="txtZiekteMin" Style="display: none"></asp:TextBox>
        <asp:TextBox runat="server" ID="txtHoursheetsLocal" Style="display: none"></asp:TextBox>
        <input type="hidden" id="txtStart" />
        <input type="hidden" id="txtEind" />
        <!-- / hidden fields -->
        <!-- ValidationSummary -->
        <asp:ValidationSummary runat="server" ID="vsum" ShowSummary="false" ShowMessageBox="true"
            HeaderText="Opslaan is mislukt door de volgende fouten:"></asp:ValidationSummary>
        <!-- / ValidationSummary -->

    Code behind:

    using System;
    using System.Linq;
    using System.Collections.Generic;
    using UrenCockpit.Business;
    using UrenCockpit.Process;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web;
    using System.Drawing;
    using Telerik.Web.UI;
    using UrenCockpit.Model;
    using System.Collections.Specialized;
    using System.Web.Script.Serialization;
     
    namespace UrenCockpit.View.Hours
    {
        public partial class UrenInvoer2 : PageExtender
        {
            private DateTime _date;
            private User _user;
     
            private const string controlOID = "OID";
            private const string controlProject = "cmbProjects";
            private const string controlSubProjects = "cmbSubProjects";
            private const string controlOmschrijving = "txtOmschrijving";
            private const string controlStarttijd = "txtStarttijd";
            private const string controlEindtijd = "txtEindtijd";
     
            private const string fieldStarttijd = "Starttijd";
            private const string fieldEindtijd = "Eindtijd";
            private const string fieldTempStarttijd = "TempStartTime";
            private const string fieldTempEindtijd = "TempEndTime";
            private const string fieldOmschrijving = "Omschrijving";
            private const string fieldSubproject = "Subproject";
            private const string fieldProject = "ProjectID";
     
            private const string commandEdit = "EditCommandColumn";
            private const string commandDelete = "DeleteCommandColumn";
            private const string commandInsert = "InitInsertButton";
     
            protected void Page_Load(object sender, EventArgs e)
            {
                if (rdpDate.SelectedDate == null)
                {
                    if (Session["selectedDate"] != null)
                    {
                        rdpDate.SelectedDate = (DateTime)Session["selectedDate"];
                    }
                    else
                    {
                        rdpDate.SelectedDate = DateTime.Now;
                    }
                }
                _date = rdpDate.SelectedDate.Value;
                _user = UserInfo.instance.User;
     
                if (!IsPostBack)
                {
                    initForm();
                    InitialiseDaysheet();
                }
                txtZiek.Attributes.Add("onclick", "openWindowMutation()");
                txtVakantie.Attributes.Add("onclick", "openWindowMutation()");
                txtOveruren.Attributes.Add("onclick", "openWindowMutation()");
            }
     
            // Initialise the min and maxvalues for the datepicker control
            private void initForm()
            {
                rdpDate.MaxDate = DateTime.Now;
                if (_user.pdx_employ_obj.InDienstSinds.HasValue)
                {
                    rdpDate.MinDate = _user.pdx_employ_obj.InDienstSinds.Value;
                }
                else
                {
                    rdpDate.MinDate = rdpDate.MaxDate;
                }
                Session["selectedDate"] = rdpDate.SelectedDate.Value;
     
                Daysheet daysheet = Daysheet.getDaysheet(_user.pdx_employ_obj, _date);
                txtGewerktMin.Text = Utility.minutesToHours(daysheet.NormaleMinuten - daysheet.GewerkteMinuten);
            }
     
            // (Re-)Initialise Daysheet section with values from database
            private void InitialiseDaysheet()
            {
                Daysheet daysheet = Daysheet.getDaysheet(_user.pdx_employ_obj, _date);
     
                if (daysheet != null)
                {
                    short contract = daysheet.NormaleMinuten;
                    short gewerkt = daysheet.GewerkteMinuten;
                    short vakantie = daysheet.VakantieMinuten;
                    short ziek = daysheet.ZiekteMinuten;
                    short overwerk = daysheet.OverMinuten;
                    int mutatie = (gewerkt + vakantie + ziek + overwerk) - contract;
     
                    SetDaySheetFields(contract, gewerkt, vakantie, ziek, overwerk, mutatie);
                }
            }
     
            // Set the fields in the Daysheet section
            private void SetDaySheetFields(short contract, short gewerkt, short vakantie, short ziek, short overwerk, int mutatie)
            {
                lblWeek.Text = "Week: " + Utility.getWeekNumber(_date).ToString();
                lblDag.Text = Utility.getWeekday(_date.DayOfWeek, false);
                lblBlocked.Text = hoursConfirmed() ? "<br>bevestigd" : "";
     
                lblContract.Text = Utility.minutesToHours(contract);
                txtVakantie.Text = Utility.minutesToHours(vakantie);
                txtZiek.Text = Utility.minutesToHours(ziek);
                txtOveruren.Text = Utility.minutesToHours(overwerk);
                lblGewerkt.Text = Utility.minutesToHours(gewerkt);
     
                lblMutatie.ForeColor = (mutatie < 0) ? Color.Red : Color.Green;
                lblMutatie.Text = Utility.minutesToHours(mutatie);
                lblMaxZiek.Text = Utility.minutesToHours(contract - gewerkt);
            }
     
            // Update current Daysheet values with entered data
            private void UpdateDaysheet()
            {
                Daysheet daysheet = Daysheet.getDaysheet(_user.pdx_employ_obj, _date);
                short totaalMinuten = CalculateTotalMinutesHoursheet();
                daysheet.GewerkteMinuten = totaalMinuten;
     
                daysheet.VakantieMinuten = (short)Utility.hourstringToMinutes(txtVakantie.Text);
                daysheet.ZiekteMinuten = (short)Utility.hourstringToMinutes(txtZiek.Text);
                daysheet.OverMinuten = (short)Utility.hourstringToMinutes(txtOveruren.Text);
     
                txtGewerktMin.Text = Utility.minutesToHours(daysheet.NormaleMinuten - daysheet.GewerkteMinuten);
     
                daysheet.Save();
                InitialiseDaysheet();
            }
     
            // Calculate the total minutes value of all the hoursheet rows for this day
            private short CalculateTotalMinutesHoursheet()
            {
                short totaalMinuten = 0;
                foreach (Hoursheet hs in getHourDetails())
                {
                    totaalMinuten += hs.Minuten;
                }
                return totaalMinuten;
            }
     
            // Fill projects combobox and set selection if selected is provided
            private void fillProjects(pdx_Subproject selected, RadComboBox rcbProjects)
            {
                rcbProjects.Items.Clear();
                foreach (pdx_Project project in getProjects())
                {
                    RadComboBoxItem item = new RadComboBoxItem();
                    item.Value = project.ProjectNumber.ToString();
                    item.Text = project.Naam;
                    rcbProjects.Items.Add(item);
                }
                if (selected != null)
                {
                    rcbProjects.SelectedValue = selected.pdx_Project.ProjectNumber.ToString();
                }
            }
     
            // Fill projects combobox without setting a selection
            private void fillProjects(RadComboBox rcbProjects)
            {
                fillProjects(null, rcbProjects);
            }
     
            // Fill subprojects combobox and set selection if selected is provided
            private void fillSubProjects(pdx_Project proj, pdx_Subproject selected, RadComboBox comboBox)
            {
                IEnumerable<pdx_Subproject> subprojects = proj.pdx_Subprojects.Where(s => s.SubAfgesloten == false);
     
                comboBox.Items.Clear();
                foreach (pdx_Subproject subproject in subprojects)
                {
                    RadComboBoxItem item = new RadComboBoxItem();
                    item.Value = subproject.SubNumber.ToString();
                    item.Text = subproject.SubNaam;
                    comboBox.Items.Add(item);
                }
                if (selected != null)
                {
                    comboBox.SelectedValue = selected.SubNumber.ToString();
                }
            }
     
            // Fill subprojects combobox based on the first project item for a user
            private void fillSubProjects(RadComboBox comboBox)
            {
                IQueryable<pdx_Project> projects = getProjects();
                fillSubProjects(projects.FirstOrDefault(), null, comboBox);
            }
     
            // Return the value of any item based by their fieldname
            private string getGridItemValue(string fieldName, GridEditableItem dataItem)
            {
                if (dataItem[fieldName].Controls.Count > 0)
                {
                    Control control = dataItem[fieldName].Controls[0];
     
                    if (control is TextBox)
                        return ((TextBox)control).Text;
                    else if (control is RadMaskedTextBox)
                        return ((RadMaskedTextBox)control).Text;
                    else if (control is RadComboBox)
                        return ((RadComboBox)control).SelectedValue;
                    else
                        return "";
                }
                else
                {
                    return dataItem[fieldName].Text;
                }
            }
     
            // Call function to check for breaks and if there are any, add them to a collection
            private List<BreakSheet> checkForBreaks(IEnumerable<CustomHourSheet> hoursheets)
            {
                int diff = 0;
                List<BreakSheet> breaks = new List<BreakSheet>();
                for (int i = 1; i < hoursheets.Count(); i++)
                {
                    string starttijd = hoursheets.ElementAt(i).Starttijd;
                    string eindtijdvorige = hoursheets.ElementAt(i - 1).Eindtijd;
                    DateTime dt1 = new DateTime(2011, 12, 31, Convert.ToInt32(eindtijdvorige.Substring(0, 2)), Convert.ToInt32(eindtijdvorige.Substring(3, 2)), 0);
                    DateTime dt2 = new DateTime(2011, 12, 31, Convert.ToInt32(starttijd.Substring(0, 2)), Convert.ToInt32(starttijd.Substring(3, 2)), 0);
                    diff = dt2.Subtract(dt1).Minutes;
     
                    if (diff > 0)
                    {
                        BreakSheet breakSheet = new BreakSheet()
                        {
                            StartTijd = starttijd,
                            EindTijd = eindtijdvorige,
                            Duur = diff
                        };
                        breaks.Add(breakSheet);
                    }
                }
                if (breaks.Count > 0)
                {
                    return breaks;
                }
                return null;
            }       
     
            private void DisableEditDisplayForAllRows()
            {
                GridDataItemCollection items = gridResult.Items;
                foreach (GridEditableItem gi in items)
                {
                    gi[commandDelete].Text = "";
                    gi[commandEdit].Text = "";
                }
            }
     
            private void DisableEditDisplay(GridItemEventArgs e)
            {
                 
                GridDataItem gridItem = (GridDataItem)e.Item;
                gridItem[commandEdit].Text = "";
                gridItem[commandDelete].Text = "";
                             
            }
     
            #region Custom CRUD actions
     
            private void DoDelete(GridEditableItem gridEditableItem)
            {
                Hoursheet hs = Hoursheet.Retrieve(getGridItemValue(controlOID, gridEditableItem));
                hs.Delete();
                UpdateDaysheet();
            }
     
            private void DoInsert(GridEditableItem gridEditableItem)
            {
                Hoursheet hs = new Hoursheet();
                if (AddOrUpdate(gridEditableItem, hs))
                {
                    Hoursheet.Insert(hs, null);
                    UpdateDaysheet();
                }
            }
     
            private void DoUpdate(GridEditableItem gridEditableItem)
            {
                Hoursheet hs = Hoursheet.Retrieve(getGridItemValue(controlOID, gridEditableItem));
                if (AddOrUpdate(gridEditableItem, hs))
                {
                    hs.Save();
                    UpdateDaysheet();
                }
            }
     
            private bool AddOrUpdate(GridEditableItem gridEditableItem, Hoursheet hs)
            {
                //Add correct date to ensure no default date is taken
                bool canSave;
     
                string date = rdpDate.SelectedDate.Value.ToString("yyyy-MM-dd");
                RadMaskedTextBox starttijd = gridEditableItem.FindControl(controlStarttijd) as RadMaskedTextBox;
                string start = starttijd.TextWithPromptAndLiterals;
     
                RadMaskedTextBox eindtijd = gridEditableItem.FindControl(controlEindtijd) as RadMaskedTextBox;
                string eind = eindtijd.TextWithPromptAndLiterals;
     
                hs.Datum = rdpDate.SelectedDate.Value;
                hs.Starttijd = DateTime.Parse(date + " " + start);
                hs.Eindtijd = DateTime.Parse(date + " " + eind);
                hs.PerNumber = _user.pdx_employ_obj.PerNumber;
                TimeSpan diff = hs.Eindtijd - hs.Starttijd;
                hs.Minuten = (short)diff.TotalMinutes;
     
                RadComboBox cmbProjects = gridEditableItem.FindControl(controlProject) as RadComboBox;
                RadComboBox cmbSubProjects = gridEditableItem.FindControl(controlSubProjects) as RadComboBox;
     
                string project = cmbProjects.SelectedValue;
                string subProject = cmbSubProjects.SelectedValue;
     
                if (subProject.IsNullOrEmpty())
                {
                    hs.SubProject = null;
                    canSave = false;
                }
                else
                {
                    hs.SubProject = long.Parse(subProject);
                    canSave = true;
                }
     
                RadTextBox omschrijving = gridEditableItem.FindControl(controlOmschrijving) as RadTextBox;
                hs.Omschrijving = omschrijving.Text;
     
                rdpDate.Enabled = true;
                return canSave;
            }
     
            #endregion
     
            #region Custom Events
     
            // Force "add new record" to show, this simulates pressing the "+" button
            protected void AddButton_Click(object sender, EventArgs e)
            {
                ListDictionary newValues = generateEmptyRow();
                gridResult.MasterTableView.InsertItem(newValues);
     
                gridResult.MasterTableView.IsItemInserted = true;
                gridResult.Rebind();
     
                GridEditableItem gridItem = (GridEditableItem)gridResult.MasterTableView.GetInsertItem();
                gridItem.FindControl(controlStarttijd).Focus();
     
                rdpDate.Enabled = false;
            }
     
            // Generates an empty row that's used to fill with data for a new row later on
            private System.Collections.Specialized.ListDictionary generateEmptyRow()
            {
                System.Collections.Specialized.ListDictionary newValues = new System.Collections.Specialized.ListDictionary();
                newValues[fieldStarttijd] = string.Empty;
                newValues[fieldEindtijd] = string.Empty;
                newValues[fieldTempStarttijd] = GetTimeForNewrow().ToString("HH:mm");
                newValues[fieldTempEindtijd] = GetTimeForNewrow().AddMinutes(15).ToString("HH:mm");
                newValues[fieldOmschrijving] = string.Empty;
                newValues[fieldSubproject] = string.Empty;
                newValues[fieldProject] = string.Empty;
                return newValues;
            }
     
            private List<LocalHoursheet> generateLocalHoursheets(List<CustomHourSheet> hoursheets)
            {
                List<LocalHoursheet> returnValue = new List<LocalHoursheet>();
                DateTime selected = rdpDate.SelectedDate.Value;
                DateTime compare = new DateTime(selected.Year, selected.Month, selected.Day, 0, 0, 0);
                foreach (CustomHourSheet chs in hoursheets)
                {
                    returnValue.Add(new LocalHoursheet()
                        {
                            DiffStartMinuten = (int)(chs.StartDatum - compare).TotalMinutes,
                            DiffEindMinuten = (int)(chs.EindDatum - compare).TotalMinutes,
                        });
                }
                return returnValue;
            }
     
            // Add or update a new record, this simulates pressing the "✔" button
            protected void SaveButton_Click(object sender, EventArgs e)
            {
                bool saved = false;
                GridEditableItem gridItem = null;
                if (gridResult.MasterTableView.IsItemInserted || gridResult.EditItems.Count > 0)
                {
                    if (gridResult.MasterTableView.IsItemInserted)
                    {
                        gridItem = (GridEditableItem)gridResult.MasterTableView.GetInsertItem();
                        DoInsert(gridItem);
                        saved = true;
                    }
                    else
                    {
                        gridItem = (GridEditableItem)gridResult.EditItems[0];
                        DoUpdate(gridItem);
                        saved = true;
                    }
                }
                if (gridItem != null && saved)
                {
                    gridItem.Edit = false;
                    gridResult.Rebind();
                }
            }
     
            // Fill subprojects with no project selected (from insert mode)
            protected void cmbProject_Insert_DataBound(object sender, EventArgs e)
            {
                GridEditableItem item = ((Control)sender).NamingContainer as GridEditableItem;
     
                RadComboBox rcbProject = (RadComboBox)sender;
                RadComboBox rcbSubProjects = (RadComboBox)item.FindControl(controlSubProjects);
     
                if (rcbProject.SelectedIndex > -1 && rcbProject.SelectedValue != "")
                {
                    pdx_Project project = pdx_Project.Retrieve(rcbProject.SelectedValue);
                    if (project != null)
                    {
                        fillSubProjects(project, null, rcbSubProjects);
                        rcbSubProjects.Focus();
                    }
                }
            }
     
            // Fill subprojects with a project selected (from edit mode)
            protected void cmbProject_Edit_DataBound(object sender, EventArgs e)
            {
                GridEditableItem item = ((Control)sender).NamingContainer as GridEditableItem;
     
                RadComboBox rcbProject = (RadComboBox)sender;
                RadComboBox rcbSubProjects = (RadComboBox)item.FindControl(controlSubProjects);
     
                if (rcbProject.SelectedIndex > -1 && rcbProject.SelectedValue != "")
                {
                    pdx_Project project = pdx_Project.Retrieve(rcbProject.SelectedValue);
     
                    CustomHourSheet hs = (CustomHourSheet)item.DataItem;
                    if (project != null && hs.pdx_Subproject != null)
                    {
                        fillSubProjects(project, hs.pdx_Subproject, rcbSubProjects);
                        rcbSubProjects.Focus();
                    }
                }
            }
     
            protected void cmbProject_TextChanged(object sender, EventArgs e)
            {
                GridEditableItem item = ((Control)sender).NamingContainer as GridEditableItem;
     
                RadComboBox rcbProject = (RadComboBox)sender;
                RadComboBox rcbSubProjects = (RadComboBox)item.FindControl(controlSubProjects);
                pdx_Project project = null;
     
                // tegengaan van invoer van een niet bestaand project
                if (rcbProject.SelectedValue == "")
                {
                    rcbProject.SelectedIndex = 0;
                }
                project = pdx_Project.Retrieve(rcbProject.SelectedValue);
                if (project != null)
                {
                    fillSubProjects(project, null, rcbSubProjects);
                    rcbSubProjects.SelectedIndex = -1;
                }
                rcbSubProjects.Text = "";
                rcbSubProjects.Focus();
            }
     
            protected void cmbProject_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
            {
                GridEditableItem item = ((Control)sender).NamingContainer as GridEditableItem;
     
                RadComboBox rcbProject = (RadComboBox)sender;
                RadComboBox rcbSubProjects = (RadComboBox)item.FindControl(controlSubProjects);
     
                if (rcbProject.SelectedValue != "")
                {
                    pdx_Project project = pdx_Project.Retrieve(rcbProject.SelectedValue);
                    if (project != null)
                    {
                        fillSubProjects(project, null, rcbSubProjects);
                        rcbSubProjects.SelectedIndex = -1;
                        rcbSubProjects.Text = "";
                        rcbSubProjects.Focus();
                    }
                }
            }
     
            protected void cmbSubProject_TextChanged(object sender, EventArgs e)
            {
                GridEditableItem item = ((Control)sender).NamingContainer as GridEditableItem;
                RadComboBox rcbSubProject = (RadComboBox)sender;
                RadTextBox txtOmschrijving = (RadTextBox)item.FindControl(controlOmschrijving);
                // tegengaan van invoer van een niet bestaand project
                if (rcbSubProject.SelectedValue == "")
                {
                    rcbSubProject.SelectedIndex = 0;
                }
                txtOmschrijving.Focus();
            }
     
            protected void rdpDate_SelectedDateChanged(object sender, Telerik.Web.UI.Calendar.SelectedDateChangedEventArgs e)
            {
                InitialiseDaysheet();
                gridResult.Rebind();
                rdpDate.Focus();
                Session["selectedDate"] = rdpDate.SelectedDate.Value;
            }
     
            #endregion
     
            # region Data Access code
     
            private DateTime GetTimeForNewrow()
            {
                DateTime returnValue = new DateTime();
     
                if (getHourDetails().Count() > 0)
                {
                    //If there already are hoursheets in the grid, determine new starttime based on max eindtijd
                    DateTime maxDateHS = getHourDetails().Where(h => h.Datum == rdpDate.SelectedDate.Value).Max(h => h.Eindtijd);
                    if (maxDateHS != null)
                    {
                        returnValue = maxDateHS;
                    }
                    // Else determine new starttime by workschedule
                    else
                    {
                        Werkrooster rooster = Werkrooster.getRoster(_user.pdx_employ_obj, _date);
                        int dayOfWeek = (int)rdpDate.SelectedDate.Value.DayOfWeek;
                        DateTime maxDateWB = rooster.Werkbloks.Where(wb => wb.Weekdag == dayOfWeek).Max(wb => wb.Starttijd.GetValueOrDefault(rdpDate.SelectedDate.Value));
     
                        // If user has a werkblok, use this
                        if (maxDateWB != null)
                        {
                            returnValue = maxDateWB;
                        }
                    }
                }
                else
                {
                    returnValue = new DateTime(2011, 12, 31, 9, 0, 0);
                }
                return returnValue;
            }
     
            private IEnumerable<Hoursheet> getHourDetails()
            {
                //Get all hoursheets for this user and date
                return Hoursheet.RetrieveAll()
                    .Where(h => h.PerNumber == _user.pdx_employ && h.Datum == _date)
                    .OrderBy(h => h.Starttijd);
            }
     
            protected IQueryable<pdx_Project> getProjects()
            {
                IQueryable<pdx_Project> projects = pdx_Project.RetrieveAll()
                    .Where(p => p.Afgesloten != true).OrderBy(p => p.Naam);
     
                projects = projects.Where(p => p.ProjectEmployeeRoles.Any(r => r.Employ == _user.pdx_employ));
                return projects;
            }
     
            private bool hoursConfirmed()
            {
                return (_user.UrenBevestigings_Obj != null && _user.UrenBevestigings_Obj.First().Datum.Value >= _date);
            }
     
            # endregion
     
            #region RadGrid Events
     
            protected void gridResult_NeedDataSource(object source, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
            {
                IEnumerable<CustomHourSheet> hoursheets = new List<CustomHourSheet>();
     
                hoursheets = from hs in getHourDetails()
                             select new CustomHourSheet
                             {
                                 Datum = hs.Datum,
                                 Eindtijd = hs.Eindtijd.ToString("HH:mm"),
                                 Minuten = hs.Minuten,
                                 OID = hs.OID,
                                 Omschrijving = hs.Omschrijving,
                                 Starttijd = hs.Starttijd.ToString("HH:mm"),
                                 Subproject = hs.SubProject,
                                 pdx_Subproject = hs.pdx_Subproject,
                                 ProjectID = hs.pdx_Subproject.pdx_Project.ProjectNumber,
                                 ProjectNaam = hs.pdx_Subproject != null ? hs.pdx_Subproject.pdx_Project.Naam : "",
                                 SubProjectNaam = hs.pdx_Subproject != null ? hs.pdx_Subproject.SubNaam : "",
                                 SubProjectID = hs.pdx_Subproject.SubNumber,
                                 TempStartTime = GetTimeForNewrow().ToString("HH:mm"),
                                 TempEndTime = GetTimeForNewrow().AddMinutes(15).ToString("HH:mm"),
                                 StartDatum = hs.Starttijd,
                                 EindDatum = hs.Eindtijd
                             };
                List<CustomHourSheet> hsList = hoursheets.ToList();
                if (hoursheets.Count() > 1)
                {
                    if (checkForBreaks(hoursheets) != null)
                    {
                        List<BreakSheet> breaksheets = checkForBreaks(hoursheets);
                        foreach (BreakSheet bs in breaksheets)
                        {
                            hsList.Add(new CustomHourSheet()
                            {
                                Eindtijd = bs.StartTijd,
                                Starttijd = bs.EindTijd,
                                Minuten = bs.Duur,
                            });
                        }
                    }
                }
                gridResult.DataSource = hsList;
                List<LocalHoursheet> hsLocal = generateLocalHoursheets(hsList);
     
                string json = GenerateJSONString(hsLocal);
                txtHoursheetsLocal.Text = json;
            }
     
            private static string GenerateJSONString(List<LocalHoursheet> hsLocal)
            {
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                string json = serializer.Serialize(hsLocal);
                return json;
            }
     
            protected void gridResult_ItemDataBound(object sender, GridItemEventArgs e)
            {
                // Viewmode, data confirmed
                bool confirmed = hoursConfirmed();
                if (e.Item is GridDataItem && !e.Item.IsInEditMode && confirmed)
                {
                    DisableEditDisplay(e);
                }
                // Editmode
                else if (e.Item is GridEditableItem && e.Item.IsInEditMode)
                {
                    RadMaskedTextBox start = e.Item.FindControl(controlStarttijd) as RadMaskedTextBox;
                    start.Focus();
                    //DisableEditDisplayForAllRows();
                }
                // Disable insert button on confirmed
                if (e.Item is GridCommandItem && confirmed)
                {
                    e.Item.FindControl(commandInsert).Parent.Visible = false;
                }
                // Disable editdisplay for breaksheets
                if ((e.Item is GridEditableItem && !e.Item.IsInEditMode))
                {
                    // Disable editdisplay for breaksheets
                    CustomHourSheet hs = (CustomHourSheet)e.Item.DataItem;
                    if (hs.Omschrijving == "" || hs.Omschrijving == null)
                    {
                        DisableEditDisplay(e);
                    }
                    // Disable editdisplay for when editmode is set
                    if (Convert.ToInt32(Session["editMode"]) == 1)
                    {
                        DisableEditDisplay(e);
                    }
                }           
            }
     
            protected void gridResult_ItemCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
            {
                if (e.CommandName == RadGrid.InitInsertCommandName)
                {
                    e.Canceled = true;
                    ListDictionary newValues = generateEmptyRow();
                    e.Item.OwnerTableView.InsertItem(newValues);
                    Session["editMode"] = 1;
                }
                if (e.CommandName == RadGrid.CancelCommandName || e.CommandName == RadGrid.PerformInsertCommandName || e.CommandName == RadGrid.UpdateCommandName || e.CommandName == RadGrid.UpdateEditedCommandName)
                {
                    rdpDate.Enabled = true;
                    Session["editMode"] = 0;
                }
                else if (e.CommandName == RadGrid.InitInsertCommandName || e.CommandName == RadGrid.EditCommandName)
                {
                    rdpDate.Enabled = false;
                    Session["editMode"] = 1;
                }
            }
     
            // Event handler that handles UpdateCommand
            protected void gridResult_UpdateCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
            {
                GridEditableItem gridEditableItem = (GridEditableItem)e.Item;
                DoUpdate(gridEditableItem);
            }
     
            // Event handler that handles DeleteCommand
            protected void gridResult_DeleteCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
            {
                GridEditableItem gridEditableItem = (GridEditableItem)e.Item;
                DoDelete(gridEditableItem);
            }
     
            // Event handler that handles InsertCommand
            protected void gridResult_InsertCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
            {
                GridEditableItem gridEditableItem = (GridEditableItem)e.Item;
                DoInsert(gridEditableItem);
            }
            #endregion
     
        }
    }

    For screenshots see attachments. They will make more clear what I mean.
  2. Yeroon
    Yeroon avatar
    87 posts
    Member since:
    Oct 2012

    Posted 19 Dec 2011 Link to this post

    I hate to bump posts, but do you have any idea's or suggestions that I might take a look at?
  3. UI for ASP.NET Ajax is Ready for VS 2017
  4. Answer
    Tsvetina
    Admin
    Tsvetina avatar
    1873 posts

    Posted 22 Dec 2011 Link to this post

    Hi Yeroon,

    The problem is that the code that the code which hides the edit buttons runs only on ItemDataBound and this event does not fire on each postback. It only fires when the grid is databound and this does not happen when the combo postbacks. So, my advice is to try moving this logic to ItemCreated or RadGrid PreRender event. Both fire on each postback.

    Let us know should you need further help with this issue.

    Greetings,
    Tsvetina
    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
Back to Top