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

First item in a RadComboBox is always consider as selected and include in an insert

1 Answer 106 Views
ComboBox
This is a migrated thread and some comments may be shown as answers.
PopaC
Top achievements
Rank 1
PopaC asked on 06 Jan 2017, 09:23 AM

Hi to all!

 

I have an issue with a RadComboBox during an insert.

 

Context:

I've made an ASP.Net app for my company to visualize dependencies between our apps by using a RadGrid for raw data and D3.JS for graphic visualization. The logic is easy: FromApp (id) is link to ToApp (id) and you have a comment field too. To do a new insertion I use the "Add new record" button from the grid, in the EditTemplate I've put one FromAppRadComboBox where you can select one app, a ToAppRadComboBox with checkboxes where you can select all the apps link to the one selected befor and a Textbox for comments. For having a record per link, I've made a CustomInsertion function called during the OnInsertCommand of the grid.

Problem:

Regardless the amount of app I check in the ToAppRCB, it will always inserts the first item in addition to the others. I manage to fix this by using a default item, but once the insertion is done, when the app want to refresh then display the grid, it breaks, because of a convertion problem (maybe because of Entity Framework).

 

Code-Behind:

001.#region
002.using ServerMap.DAL;
003.using System;
004.using System.Collections;
005.using System.Collections.Generic;
006.using System.Data;
007.using System.Data.SqlClient;
008.using System.Linq;
009.using System.Web;
010.using System.Web.Configuration;
011.using System.Web.UI;
012.using System.Web.UI.WebControls;
013.using Telerik.Web.UI;
014. 
015.#endregion
016. 
017.namespace ServerMap
018.{
019.    public partial class ApplicationsDependencies : Page
020.    {
021.        private List<int> selectedToApplications = new List<int>();
022. 
023.        protected void Page_Load(object sender, EventArgs e)
024.        {
025.            if (!IsPostBack)
026.            {
027.                string FromApplicationName = HttpContext.Current.Request.QueryString["FromApplicationId"];
028.                string ToApplicationName = HttpContext.Current.Request.QueryString["ToApplicationId"];
029. 
030.                if (!string.IsNullOrEmpty(FromApplicationName) || !string.IsNullOrEmpty(ToApplicationName))
031.                {
032.                    string filterColumn = "",
033.                        filterValue = "";
034.                    if (!string.IsNullOrEmpty(FromApplicationName))
035.                    {
036.                        filterColumn = "FromAppId";
037.                        filterValue = FromApplicationName;
038.                    }
039.                    else
040.                    {
041.                        filterColumn = "ToAppId";
042.                        filterValue = ToApplicationName;
043.                    }
044. 
045.                    ApplicationDependency.MasterTableView.FilterExpression =
046.                        String.Format(
047.                            "(it.[{0}] = {1}) && ((it.FromApplication.[IT_DECOMMISSION_DATE] is null) && (it.ToApplication.[IT_DECOMMISSION_DATE] is null))",
048.                            filterColumn, filterValue);
049.                    ;
050.                    GridColumn gridColumn = ApplicationDependency.MasterTableView.GetColumnSafe(filterColumn);
051.                    gridColumn.CurrentFilterFunction = GridKnownFunction.EqualTo;
052.                    gridColumn.CurrentFilterValue = filterValue;
053.                    ApplicationDependency.Rebind();
054.                }
055.                else
056.                {
057.                    ApplicationDependency.MasterTableView.FilterExpression =
058.                        "((it.FromApplication.[IT_DECOMMISSION_DATE] is null) && (it.ToApplication.[IT_DECOMMISSION_DATE] is null))";
059.                    ApplicationDependency.Rebind();
060.                }
061.            }
062.        }
063. 
064.        //protected void ToApplicationCombobox_OnDataBound(object sender, EventArgs e)
065.        //{
066.        //    var combo = (RadComboBox)sender;
067.        //    combo.Items.Insert(0, new RadComboBoxItem("Please select an application", "-1"));
068.        //}
069. 
070.        //protected void PreSelectItem(string comboboxname, string field, GridItemEventArgs e)
071.        //{
072.        //    GridEditableItem editableItem = e.Item as GridEditableItem;
073. 
074.        //    RadComboBox combo = (RadComboBox)editableItem.FindControl(comboboxname);
075.        //    if (!string.IsNullOrEmpty(editableItem[field].Text) && editableItem[field].Text != " ")
076.        //    {
077.        //        RadComboBoxItem selectedItem = new RadComboBoxItem
078.        //        {
079.        //            Text = editableItem[field].Text.ToString(),
080.        //            Value = editableItem[field].Text.ToString()
081.        //        };
082.        //        combo.Items.Add(selectedItem);
083.        //        if (combo.CheckBoxes)
084.        //        {
085.        //            combo.Items.FindItemByValue(editableItem[field].Text).Checked = true;
086.        //        }
087.        //        selectedItem.DataBind();
088.        //        Session[field] = selectedItem.Value;
089.        //    }
090.        //}
091. 
092.        protected void CustomCreation(object sender, GridCommandEventArgs e)
093.        {
094.            var FromDropDown = (RadComboBox)e.Item.FindControl("FromApplicationCombobox");
095.            var ToDropDown = (RadComboBox)e.Item.FindControl("ToApplicationCombobox");
096.            var CommentsTextBox = (RadTextBox)e.Item.FindControl("CommentsTextBox");
097. 
098.            try
099.            {
100.                using (var db = new ServerMapContext())
101.                {
102.                    System.Data.Entity.DbSet<AppToAppDependency> context = db.Set<AppToAppDependency>();
103. 
104.                    foreach (RadComboBoxItem item in ToDropDown.CheckedItems)
105.                    {
106.                        if (!LinkExists(Convert.ToInt32(FromDropDown.SelectedValue), Convert.ToInt32(item.Value)))
107.                        {
108.                            var itemToInsert = new AppToAppDependency
109.                            {
110.                                FromApp = Convert.ToInt32(FromDropDown.SelectedValue),
111.                                ToApp = Convert.ToInt32(item.Value),
112.                                Comment = CommentsTextBox.Text
113.                            };
114.                            context.Attach(itemToInsert);
115.                            context.Add(itemToInsert);
116.                            db.SaveChanges();
117.                        }
118.                    }
119.                }
120.            }
121.            catch (EntityDataSourceValidationException validationException)
122.            {
123.                ApplicationDependency.Controls.Add(new LiteralControl("ENTITY: Unable to insert application dependencie(s). Reason: " + validationException.Message));
124.                e.Canceled = true;
125.            }
126.            catch (Exception ex)
127.            {
128.                ApplicationDependency.Controls.Add(new LiteralControl("Unable to insert application dependencie(s). Reason: " + ex.Message));
129.                e.Canceled = true;
130.            }
131.            finally
132.            {
133.                e.Canceled = false;
134.            }
135.        }
136. 
137.        protected bool LinkExists(int from, int to)
138.        {
139.            try
140.            {
141.                using (var db = new ServerMapContext())
142.                {
143.                    System.Data.Entity.DbSet<AppToAppDependency> context = db.Set<AppToAppDependency>();
144. 
145.                    var test = context.Where(x => x.FromApp == from && x.ToApp == to);
146. 
147.                    if (test.Any())
148.                    {
149.                        return true;
150.                    }
151.                    return false;
152.                }
153.            }
154.            catch (Exception ex)
155.            {
156.                ApplicationDependency.Controls.Add(new LiteralControl(ex.Message));
157.                return false;
158.            }
159.        }
160. 
161.        //protected void AppCombobox_ItemsRequested(object sender, RadComboBoxItemsRequestedEventArgs e)
162.        //{
163.        //    InitAppList(sender);
164.        //}
165. 
166.        //protected void InitAppList(object sender)
167.        //{
168.        //    IList<Applications_List> apps = null;
169.        //    using (var db = new ServerMapContext())
170.        //    {
171.        //        System.Data.Entity.DbSet<Applications_List> context = db.Set<Applications_List>();
172. 
173.        //        apps = context.Select(x => x).Where(x => x.IT_DECOMMISSION_DATE == null).OrderBy(x => x.BU_APP_NAME).ToList();
174.        //    }
175. 
176.        //    RadComboBox Combobox = (RadComboBox)sender;
177. 
178.        //    foreach (var app in apps)
179.        //    {
180.        //        RadComboBoxItem item = new RadComboBoxItem();
181.        //        item.Text = app.BU_APP_NAME;
182.        //        item.Value = Convert.ToString(app.id);
183.        //        if (!string.IsNullOrEmpty(item.Text) && item.Text != " ")
184.        //        {
185.        //            Combobox.Items.Add(item);
186.        //            item.DataBind();
187.        //        }
188.        //    }
189.        //}
190.    }
191.}

 

ASPX:

001.<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true"
002.    CodeBehind="ApplicationsDependencies.aspx.cs" Inherits="ServerMap.ApplicationsDependencies" %>
003. 
004.<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder" runat="server">
005. 
006.    <telerik:RadScriptManager runat="server" />
007.    <telerik:RadSkinManager runat="server" Skin="Metro" />
008. 
009.    <telerik:RadGrid
010.        ID="ApplicationDependency"
011.        runat="server"
012.        DataSourceID="AppToAppDependenciesDS"
013.        AutoGenerateColumns="False"
014.        AllowPaging="True"
015.        AllowFilteringByColumn="True"
016.        PageSize="50"
017.        AllowCustomPaging="True"
018.        AllowAutomaticDeletes="True"
019.        AllowAutomaticInserts="True"
020.        AllowAutomaticUpdates="False"
021.        ClientSettings-AllowColumnsReorder="false"
022.        OnInsertCommand="CustomCreation"
023.        AllowSorting="True"
024.        CellSpacing="0"
025.        GridLines="None"
026.        Height="800px">
027. 
028.        <ClientSettings>
029.            <Scrolling
030.                ScrollHeight="700px"
031.                SaveScrollPosition="True"
032.                AllowScroll="true"
033.                UseStaticHeaders="True"></Scrolling>
034.        </ClientSettings>
035. 
036.        <MasterTableView
037.            CommandItemDisplay="TopAndBottom"
038.            AutoGenerateColumns="False"
039.            DataKeyNames="id"
040.            DataSourceID="AppToAppDependenciesDS">
041. 
042.            <PagerStyle AlwaysVisible="true" />
043. 
044.            <SortExpressions>
045.                <telerik:GridSortExpression SortOrder="Ascending" FieldName="FromApplication.BU_APP_NAME" />
046.            </SortExpressions>
047. 
048.            <Columns>
049. 
050.                <telerik:GridEditCommandColumn
051.                    UniqueName="EditCommand"
052.                    Exportable="false">
053.                </telerik:GridEditCommandColumn>
054. 
055.                <telerik:GridBoundColumn
056.                    DataField="id"
057.                    DataType="System.Int32"
058.                    FilterControlAltText="Filter id column"
059.                    HeaderText="id"
060.                    ReadOnly="True"
061.                    SortExpression="id"
062.                    UniqueName="id"
063.                    CurrentFilterFunction="NoFilter"
064.                    AutoPostBackOnFilter="true"
065.                    Visible="False"
066.                    Exportable="true">
067.                    <ColumnValidationSettings>
068.                        <ModelErrorMessage Text="" />
069.                    </ColumnValidationSettings>
070.                </telerik:GridBoundColumn>
071. 
072.                <telerik:GridBoundColumn
073.                    UniqueName="FromAppId"
074.                    Visible="false"
075.                    ReadOnly="true"
076.                    Exportable="false">
077.                    <ColumnValidationSettings>
078.                        <ModelErrorMessage Text="" />
079.                    </ColumnValidationSettings>
080.                </telerik:GridBoundColumn>
081. 
082.                <telerik:GridHyperLinkColumn
083.                    UniqueName="FromApp"
084.                    DataNavigateUrlFormatString="~/ApplicationListNew.aspx?ApplicationName={0}"
085.                    DataNavigateUrlFields="FromApplication.BU_APP_NAME"
086.                    HeaderText="From App"
087.                    DataTextField="FromApplication.BU_APP_NAME"
088.                    AllowSorting="true"
089.                    AutoPostBackOnFilter="true"
090.                    CurrentFilterFunction="EqualTo"
091.                    AllowFiltering="true">
092.                    <ItemStyle Wrap="false" />
093.                    <FilterTemplate>
094.                        <telerik:RadComboBox
095.                            Skin="Metro"
096.                            ID="FromAppFilterCombobox"
097.                            Sort="Ascending"
098.                            DataSourceID="ApplicationDS"
099.                            DataTextField="BU_APP_NAME"
100.                            DataValueField="BU_APP_NAME"
101.                            AppendDataBoundItems="true"
102.                            OnClientSelectedIndexChanged=" FromApplicationNameChanged "
103.                            SelectedValue='<%# Container.OwnerTableView.GetColumn("FromApp").CurrentFilterValue %>'
104.                            runat="server"
105.                            Width="400px">
106.                            <Items>
107.                                <telerik:RadComboBoxItem Text="All" />
108.                            </Items>
109.                        </telerik:RadComboBox>
110.                        <telerik:RadScriptBlock ID="FromAppRadScriptBlock" runat="server">
111.                            <script type="text/javascript">
112.                                function FromApplicationNameChanged(sender, args) {
113.                                    var tableView = $find("<%# Container.OwnerTableView.ClientID %>");
114.                                    tableView.filter("FromApp", args.get_item().get_value(), "EqualTo");
115.                                }
116.                            </script>
117.                        </telerik:RadScriptBlock>
118.                    </FilterTemplate>
119.                </telerik:GridHyperLinkColumn>
120. 
121.                <telerik:GridBoundColumn
122.                    UniqueName="ToAppId"
123.                    Visible="false"
124.                    ReadOnly="true"
125.                    Exportable="false">
126.                    <ColumnValidationSettings>
127.                        <ModelErrorMessage Text="" />
128.                    </ColumnValidationSettings>
129.                </telerik:GridBoundColumn>
130. 
131.                <telerik:GridHyperLinkColumn
132.                    UniqueName="ToApp"
133.                    DataNavigateUrlFormatString="~/ApplicationListNew.aspx?ApplicationName={0}"
134.                    DataNavigateUrlFields="ToApplication.BU_APP_NAME"
135.                    HeaderText="To App"
136.                    DataTextField="ToApplication.BU_APP_NAME"
137.                    AllowSorting="true"
138.                    AutoPostBackOnFilter="true"
139.                    CurrentFilterFunction="EqualTo"
140.                    AllowFiltering="true">
141.                    <ItemStyle Wrap="false" />
142.                    <FilterTemplate>
143.                        <telerik:RadComboBox
144.                            Skin="Metro"
145.                            ID="ToAppFilterCombobox"
146.                            Sort="Ascending"
147.                            DataSourceID="ApplicationDS1"
148.                            DataTextField="BU_APP_NAME"
149.                            DataValueField="BU_APP_NAME"
150.                            AppendDataBoundItems="true"
151.                            OnClientSelectedIndexChanged=" ToApplicationNameChanged "
152.                            SelectedValue='<%# Container.OwnerTableView.GetColumn("ToApp").CurrentFilterValue %>'
153.                            runat="server"
154.                            Width="400px">
155.                            <Items>
156.                                <telerik:RadComboBoxItem Text="All" />
157.                            </Items>
158.                        </telerik:RadComboBox>
159.                        <telerik:RadScriptBlock ID="ToAppRadScriptBlock" runat="server">
160.                            <script type="text/javascript">
161.                                function ToApplicationNameChanged(sender, args) {
162.                                    var tableView = $find("<%# Container.OwnerTableView.ClientID %>");
163.                                    tableView.filter("ToApp", args.get_item().get_value(), "EqualTo");
164.                                }
165.                            </script>
166.                        </telerik:RadScriptBlock>
167.                    </FilterTemplate>
168.                </telerik:GridHyperLinkColumn>
169. 
170.                <telerik:GridBoundColumn
171.                    DataField="Comment"
172.                    FilterControlAltText="Filter Comment column"
173.                    HeaderText="Comments"
174.                    SortExpression="Comment"
175.                    UniqueName="Comments"
176.                    CurrentFilterFunction="NoFilter">
177.                    <ColumnValidationSettings>
178.                        <ModelErrorMessage Text="" />
179.                    </ColumnValidationSettings>
180.                </telerik:GridBoundColumn>
181. 
182.                <telerik:GridButtonColumn
183.                    CommandName="Delete"
184.                    Text="Delete"
185.                    HeaderText="Delete"
186.                    UniqueName="DeleteCommand"
187.                    Exportable="false"
188.                    ButtonType="ImageButton"
189.                    ImageUrl="Images/delete.png">
190.                </telerik:GridButtonColumn>
191. 
192.            </Columns>
193.            <EditFormSettings EditFormType="Template">
194.                <FormStyle BackColor="White" />
195.                <FormTemplate>
196.                    <table
197.                        id="Table4"
198.                        cellspacing="1"
199.                        cellpadding="5"
200.                        width="auto"
201.                        border="0"
202.                        class="module"
203.                        style="padding: 20px;">
204. 
205.                        <tr>
206.                            <td>From Application:</td>
207.                            <td>
208.                                <telerik:RadComboBox
209.                                    Skin="Metro"
210.                                    ID="FromApplicationComboBox"
211.                                    Sort="Ascending"
212.                                    DataSourceID="ApplicationDS"
213.                                    DataTextField="BU_APP_NAME"
214.                                    DataValueField="id"
215.                                    AppendDataBoundItems="true"
216.                                    SelectedValue='<%# Bind("FromApp") %>'
217.                                    runat="server"
218.                                    Width="300">
219.                                </telerik:RadComboBox>
220.                                <%--<telerik:RadComboBox
221.                                    ID="FromApplicationComboBox"
222.                                    runat="server"
223.                                    Width="300"
224.                                    DataTextField="BU_APP_NAME"
225.                                    DataValueField="id"
226.                                    AllowCustomText="false"
227.                                    EnableLoadOnDemand="true"
228.                                    MarkFirstMatch="true"
229.                                    OnItemsRequested="AppCombobox_ItemsRequested"
230.                                    OnClientItemChecking="clientItemChecking"
231.                                    Text='<%# Bind("FromApp") %>'>
232.                                </telerik:RadComboBox>--%>
233.                            </td>
234.                        </tr>
235.                        <tr>
236.                            <td>To Application:</td>
237.                            <td>
238.                                <telerik:RadComboBox
239.                                    Skin="Metro"
240.                                    ID="ToApplicationCombobox"
241.                                    ClientIDMode="Static"
242.                                    Sort="Ascending"
243.                                    DataSourceID="ApplicationDS1"
244.                                    DataTextField="BU_APP_NAME"
245.                                    DataValueField="id"
246.                                    AppendDataBoundItems="true"
247.                                    SelectedValue='<%# Bind("ToApp") %>'
248.                                    runat="server"
249.                                    CheckBoxes="true"
250.                                    Width="300"
251.                                    AutoPostBack="False">
252.                                    <%--<DefaultItem
253.                                        Text="Please select an application"
254.                                        Value="" />--%>
255.                                </telerik:RadComboBox>
256.                                <%--<telerik:RadComboBox
257.                                    ID="ToApplicationCombobox"
258.                                    runat="server"
259.                                    Width="300"
260.                                    DataTextField="BU_APP_NAME"
261.                                    DataValueField="id"
262.                                    MarkFirstMatch="true"
263.                                    AllowCustomText="false"
264.                                    EnableLoadOnDemand="true"
265.                                    RenderMode="Lightweight"
266.                                    CheckBoxes="true"
267.                                    CheckedItemsTexts="FitInInput"
268.                                    OnItemsRequested="AppCombobox_ItemsRequested"
269.                                    OnClientItemChecked=" OnClientItemChecked "
270.                                    Text='<%# Bind("ToApp") %>'>
271.                                </telerik:RadComboBox>--%>
272.                            </td>
273.                        </tr>
274.                        <tr>
275.                            <td>Comments:</td>
276.                            <td>
277.                                <telerik:RadTextBox
278.                                    ID="CommentsTextBox"
279.                                    Width="300"
280.                                    runat="server"
281.                                    Text='<%# Bind("Comment") %>'>
282.                                </telerik:RadTextBox>
283.                            </td>
284. 
285.                        </tr>
286.                        <tr>
287.                            <asp:CustomValidator
288.                                ID="CustomValidator1"
289.                                ErrorMessage="Please choose at least one app to link!"
290.                                ClientValidationFunction="selectionFormValidationGroup"
291.                                ValidationGroup="SelectionFormValidationGroup"
292.                                runat="server"
293.                                CssClass="validator" />
294.                            <td align="right" colspan="2" style="padding-top: 15px;">
295.                                <asp:Button
296.                                    ID="btnUpdate"
297.                                    Text='<%# (Container is GridEditFormInsertItem) ? "Insert" : "Update" %>'
298.                                    runat="server"
299.                                    CommandName='<%# (Container is GridEditFormInsertItem) ? "PerformInsert" : "Update" %>'
300.                                    ValidationGroup="SelectionFormValidationGroup"></asp:Button
301.                                <asp:Button
302.                                    ID="btnCancel"
303.                                    Text="Cancel"
304.                                    runat="server"
305.                                    CausesValidation="False"
306.                                    CommandName="Cancel" />
307.                            </td>
308.                        </tr>
309.                    </table>
310.                </FormTemplate>
311.            </EditFormSettings>
312.        </MasterTableView>
313.    </telerik:RadGrid>
314. 
315.    <asp:EntityDataSource
316.        ID="AppToAppDependenciesDS"
317.        runat="server"
318.        ConnectionString="name=ServerMapContext"
319.        DefaultContainerName="ServerMapContext"
320.        EnableFlattening="False"
321.        EntitySetName="AppToAppDependencies"
322.        Include="FromApplication, ToApplication"
323.        EnableUpdate="true"
324.        EnableInsert="true"
325.        EnableDelete="True"
326.        Where="(it.FromApplication.[IT_DECOMMISSION_DATE] is null) && it.ToApplication.[IT_DECOMMISSION_DATE] is null">
327.    </asp:EntityDataSource>
328. 
329.    <asp:EntityDataSource
330.        ID="ApplicationDS"
331.        runat="server"
332.        ConnectionString="name=ServerMapContext"
333.        DefaultContainerName="ServerMapContext"
334.        EnableFlattening="False"
335.        EntitySetName="Applications_List"
336.        EntityTypeFilter="Applications_List"
337.        Select="it.[id], it.[BU_APP_NAME],it.[IT_DECOMMISSION_DATE]"
338.        OrderBy="it.[BU_APP_NAME]"
339.        Where="(it.[IT_DECOMMISSION_DATE] is null)">
340.    </asp:EntityDataSource>
341. 
342.    <asp:EntityDataSource
343.        ID="ApplicationDS1"
344.        runat="server"
345.        ConnectionString="name=ServerMapContext"
346.        DefaultContainerName="ServerMapContext"
347.        EnableFlattening="False"
348.        EntitySetName="Applications_List"
349.        EntityTypeFilter="Applications_List"
350.        Select="it.[id], it.[BU_APP_NAME],it.[IT_DECOMMISSION_DATE]"
351.        OrderBy="it.[BU_APP_NAME]"
352.        Where="(it.[IT_DECOMMISSION_DATE] is null)">
353.    </asp:EntityDataSource>
354. 
355.    <script type="text/javascript">
356.        function selectionFormValidationGroup(sender, args) {
357.            var combos = $telerik.$(".selection-form .RadComboBox");
358. 
359.            args.IsValid = true;
360. 
361.            for (var i = 0; i < combos.length; i++) {
362.                if (combos[i].value == "-1") {
363.                    args.IsValid = false;
364.                    break;
365.                }
366.            }
367.        }
368.    </script>
369.
</asp:Content>

1 Answer, 1 is accepted

Sort by
0
Konstantin Dikov
Telerik team
answered on 11 Jan 2017, 08:36 AM
Hello,

The scenario seems rather complex and it will be difficult to guess what could be the root of the problem, especially since including a DefaultValue resolves the initial problem. Can you please elaborate what error is thrown after the insert and share the full stack trace of it? Additionally, can you please elaborate what is the data type of the "ToApp" field bound to the RadComboBox?

On a side note, if you can prepare a sample, runnable project replicating the issue and attach it in a regular support ticket, we will be able to debug it locally.


Regards,
Konstantin Dikov
Telerik by Progress
Try our brand new, jQuery-free Angular 2 components built from ground-up which deliver the business app essential building blocks - a grid component, data visualization (charts) and form elements.
Tags
ComboBox
Asked by
PopaC
Top achievements
Rank 1
Answers by
Konstantin Dikov
Telerik team
Share this question
or