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

radgrid edit form template weird display issues

1 Answer 127 Views
Grid
This is a migrated thread and some comments may be shown as answers.
ADT
Top achievements
Rank 1
ADT asked on 06 Dec 2012, 11:05 PM
I have a radgrid that uses edit form templates. I open the grid and have all the fields in edit mode and hide the actual item row, to show only the edit item templates. I use a dropdown and textbox to have them choose a distributor and the # of records. In testing I generally use 10 #'s. When the button is clicked and the grid is populated. This form is used almost in the way that access forms are used, so they can input lots of records at once without having to click submit/add new over and over.

I am having an issue with the actual template itself, sometimes the fields go into weird positions and do not line up like the others. This can occur randomly but generally occurs after I click save and usually only occurs on the second to last record.

Anyone have ideas why this might occur? Would it be better to use a custom user template instead (can I still have this functionality with that)?

I will post my code below:
aspx:
<%@ Page Title="" Language="VB" MasterPageFile="~/MasterNoBanner.master" AutoEventWireup="false" CodeFile="CropProtectionTransactionsAdd.aspx.vb" Inherits="CP_TransactionsAdd" %>
 
<%@ Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" %>
 
<asp:Content ID="Content1" ContentPlaceHolderID="cphBodyText" Runat="Server">
    <div style="width: 980px; min-height:800px; clear : both; border-bottom: 0px solid black;" >
 
        
        <telerik:RadCodeBlock ID="RadCodeBlock1" runat="server">
 
            <script type="text/javascript">
                function CatchKeyPress(sender, args) {
                    if (args.get_keyCode() == 13) { //Enter Key
                        var e = args.get_domEvent().rawEvent;
                        e.returnValue = false;
                        e.cancelBubble = true;
                        if (e.stopPropagation) {
                            e.preventDefault();
                            e.stopPropagation();
                        }
                    }
 
                    if (args.get_keyCode() == 27) { //esca Key
                        var e = args.get_domEvent().rawEvent;
                        e.returnValue = false;
                        e.cancelBubble = true;
                        if (e.stopPropagation) {
                            e.preventDefault();
                            e.stopPropagation();
                        }
                    }
                    if (args.get_keyCode() == 8 || args.get_keyCode() == 46) { //backspace Key
                        var e = args.get_domEvent().rawEvent;
                        e.returnValue = false;
                        e.cancelBubble = true;
                        if (e.stopPropagation) {
                            e.preventDefault();
                            e.stopPropagation();
                        }
                    }
 
                }
 
                function gridCommand(sender, args) {
                    var command = args.get_commandName();
                    if (command == "DeleteRow" || command == "CopyPaste" || command == "SaveChanges" || command == "CancelChanges" || command == "Sort" || command == "Page" || command == "Filter" || command == "ChangePageSize") {
                        //cancel the additional check in body.onunload
                        window.editInProgress = false;
                    }
                }
                function gridCommandCustom(evt) {
                    var command = evt
                    if (command == "DeleteRow" || command == "CopyPaste" || command == "SaveChanges" || command == "CancelChanges" || command == "Sort" || command == "Page" || command == "Filter" || command == "ChangePageSize" || command == "AddRecord") {
                        //cancel the additional check in body.onunload
                        window.editInProgress = false;
                    }
                }
                function verifyCancelChanges() {
                    if (window.editInProgress) {
                        //alert(window.editInProgress.tostring);
                        $find("<%=RadAjaxManager1.ClientID %>").ajaxRequest();
                    }
 
                }
                function updateEdit() {
                    window.editInProgress = true;
                }
                window.onbeforeunload = function (evt) {
                    // alert(window.editInProgress);
                    verifyCancelChanges();
 
                }
 
                function Selected(rowIndex, eventArgs) {
                    var grid = $find("<%= RadGrid1.ClientID %>");
                    if (grid) {
                        if (rowIndex == -1) {
 
                            var masterTable = $find("<%= RadGrid1.ClientID %>").get_masterTableView();
                            //                            var editForm = $telerik.$(".rgEditForm")[0];
                            //                            var txtSize2 = $telerik.findElement(editForm, "txtSize");
                            var InsertItems = masterTable.get_insertItem();
                            // var insertItem = InsertItems[0];
                            var txtSize = $(masterTable.get_insertItem()).find("input[id*='txtSize']").get(0);
                            txtSize.value = eventArgs.get_item().get_attributes().getAttribute("Size");
                            var txtManufacturer = $(masterTable.get_insertItem()).find("input[id*='txtManufacturer']").get(0);
                            txtManufacturer.value = eventArgs.get_item().get_attributes().getAttribute("SupplierName");
                        }
                        else {
                            var EditItems = grid.get_editItems();
                            var editItem = EditItems[rowIndex];
 
                            var txtSize = $(editItem.get_editFormItem()).find("input[id*='txtSize']").get(0);
                            txtSize.value = eventArgs.get_item().get_attributes().getAttribute("Size");
                            var txtManufacturer = $(editItem.get_editFormItem()).find("input[id*='txtManufacturer']").get(0);
                            txtManufacturer.value = eventArgs.get_item().get_attributes().getAttribute("SupplierName");
                        }
 
                    }
                }
 
 
 
 
                function LoadShipTo(combo, eventArqs) {
                    var item = eventArqs.get_item();
                    var grid = $find("<%= RadGrid1.ClientID %>");
                    var EditItems = grid.get_editItems();
                    var rowIndex = combo.get_attributes().getAttribute("ddItemIndex")
                    var editItem = EditItems[rowIndex];
                    //var radcomboShipTo = $(editItem.get_editFormItem()).find("input[id*='ddlShipTo']").get(0);
                    // var ComboShipTo = combo.get_attributes().getAttribute("ddClientID");
                    var ComboShipTo = $find(combo.get_attributes().getAttribute("ddClientID"));
                    // ComboShipTo.set_text("Loading...");
                    //radcomboShipTo.show
                    //   radcomboShipTo.set_text("Loading...");
                    ComboShipTo.requestItems(item.get_value(), false);
                    //  ComboShipTo.focus();
                }
 
                function ShipToLoaded(combo, eventArgs) {
                    if (combo.get_items().get_count() > 0) {
                        // pre-select the first item
                        combo.set_text(combo.get_items().getItem(0).get_text());
                        combo.get_items().getItem(0).highlight();
                        //combo.showDropDown();
                    }
                }
 
 
                function UpdateExtension(rowIndex, extensionid, eventArqs) {
                    var grid = $find("<%= RadGrid1.ClientID %>");
                    var EditItems = grid.get_editItems();
                    var editItem = EditItems[rowIndex];
                    var txtPrice = $(editItem.get_editFormItem()).find("input[id*='txtPrice']").get(0);
                    var txtQuantity = $(editItem.get_editFormItem()).find("input[id*='txtQuantity']").get(0);
                    var txtExtension = $find(extensionid);
                    var intPrice = txtPrice.value;
                    var intQuantity = txtQuantity.value;
                    var intTotal = intPrice * intQuantity
                    if (intQuantity < 0) {
                        intTotal = (Math.ceil(intTotal * 100)) / 100;
                    }
                    else {
                        intTotal = (Math.floor(intTotal * 100)) / 100;
                    }
                    txtExtension.set_value(intTotal);
                }
 
               </script>
 
        </telerik:RadCodeBlock>
            <telerik:RadWindowManager runat="server" ID="RadWindowManager1">
    </telerik:RadWindowManager>
         <telerik:RadFormDecorator ID="RadFormDecorator1" runat="server" DecoratedControls="Default,Select,Textbox"
        EnableRoundedCorners="false" />
 
 
    <telerik:RadAjaxManager ID="RadAjaxManager1" runat="server" OnAjaxRequest="RadAjaxManager1_AjaxRequest">
        <AjaxSettings>
                    <telerik:AjaxSetting AjaxControlID="RadAjaxManager1">
                <UpdatedControls>
                    <telerik:AjaxUpdatedControl ControlID="RadGrid1" LoadingPanelID="RadAjaxLoadingPanel1"  />
                    <telerik:AjaxUpdatedControl ControlID="lblError" />
                </UpdatedControls>
            </telerik:AjaxSetting>
            <telerik:AjaxSetting AjaxControlID="RadAjaxManager1" EventName="RadGrid1_PreRender">
                <UpdatedControls>
                    <telerik:AjaxUpdatedControl ControlID="RadGrid1" LoadingPanelID="RadAjaxLoadingPanel1"  />
                    <telerik:AjaxUpdatedControl ControlID="lblError" />
                </UpdatedControls>
            </telerik:AjaxSetting>
                        <telerik:AjaxSetting AjaxControlID="RadGrid1">
                <UpdatedControls>
                    <telerik:AjaxUpdatedControl ControlID="RadGrid1"  LoadingPanelID="RadAjaxLoadingPanel1" />
                    <telerik:AjaxUpdatedControl ControlID="lblError" />
                </UpdatedControls>
            </telerik:AjaxSetting>
            <telerik:AjaxSetting AjaxControlID="btnGrid">
                <UpdatedControls>
                <telerik:AjaxUpdatedControl ControlID="RadGrid1"  LoadingPanelID="RadAjaxLoadingPanel1" />
                                        <telerik:AjaxUpdatedControl ControlID="lblError" />
                    
                </UpdatedControls>
            </telerik:AjaxSetting>
        </AjaxSettings>
    </telerik:RadAjaxManager>
 
    <telerik:RadAjaxLoadingPanel ID="RadAjaxLoadingPanel1" runat="server" Height="16px"
            Width="16px" />
 
<br />
            <div style='width: 95%;'>
<table width="100%" align="left" border="0" cellpadding="2" cellspacing=0>
    <tr>
        <td width="175px" align="right">Choose Distributor to add:</td>
        <td><telerik:RadComboBox ID="ddlDistributors" DataSourceID="dsDistributors" EmptyMessage="Choose..." AllowCustomText="false" MarkFirstMatch="true"  DataTextField="DistributorName" DataValueField="CPDistributorID" runat="server">
            <Items>
                                                <telerik:RadComboBoxItem Value="0" Text="" Selected="true" />
                                            </Items>
        </telerik:RadComboBox></td></tr>
    <tr>
    <td width="175px"  align="right"># of Rows (estimate) to add: </td>
    <td><telerik:RadNumericTextBox ID="txtRows" runat="server" MinValue="0" MaxValue="100" Width="75px">
<NumberFormat DecimalDigits="0" GroupSeparator="" /></telerik:RadNumericTextBox> <telerik:RadButton runat="server" ID="btnGrid" Text="Add Records" ></telerik:RadButton></td></tr>
</table>
</div>
<br /><br /><br />
<asp:Label id="lblError" runat="server" Text="asdf"  Visible="true"></asp:Label>
       <telerik:RadGrid ID="RadGrid1" 
            AllowFilteringByColumn="false"
            AllowSorting="false"  runat="server" ShowFooter="false" ShowHeader="false" ShowGroupPanel="false" ShowStatusBar="false"
            AutoGenerateColumns="False" CellSpacing="0" AllowMultiRowEdit="True" PageSize="10"
            Width="98%" AllowPaging="false" Height="600px"  OnItemDataBound="OnItemDataBoundHandler" ViewStateMode="Enabled" >
            <ClientSettings>
             
<Selecting AllowRowSelect="True"></Selecting>
 
<ClientEvents OnKeyPress="CatchKeyPress"></ClientEvents>
 
            <Scrolling AllowScroll="true" UseStaticHeaders="true"></Scrolling>
        </ClientSettings>
         
 
            <MasterTableView EditMode="EditForms" DataKeyNames="TransactionID"  CommandItemDisplay="Top"  PagerStyle-AlwaysVisible="false" InsertItemDisplay="Bottom" InsertItemPageIndexAction="ShowItemOnCurrentPage" ViewStateMode="Enabled"
   NoMasterRecordsText="Choose a distributor and # of rows to add to the grid. You can add more rows by clicking the 'Add Records' button again." >
             
                <CommandItemTemplate>
                 
          <table width="100%">
          <tr>
            <td align="right"><asp:LinkButton ID="btnInsertProduct" OnClientClick="gridCommandCustom('AddRecord')" runat="server" CommandName="InsertProduct" Visible="true" style='display: none;'><img style="border:0px" alt="" src="Images/AddRecord.gif" />- Add New Product</asp:LinkButton>        
            <asp:LinkButton ID="btnCancelChanges" runat="server" OnClientClick="gridCommandCustom('CancelChanges');" CommandArgument="CancelChanges" CommandName="CancelChanges" Visible="true"><img style="border:0px" alt="" src="Images/Cancel.gif" />- Clear all Changes </asp:LinkButton>      
 <asp:LinkButton ID="btnSaveChanges" runat="server" CommandArgument="SaveChanges" CommandName="SaveChanges"  OnClientClick="gridCommandCustom('SaveChanges');" Visible="true"><img style="border:0px" alt="" src="Images/Update.gif" />- Save All changes</asp:LinkButton>
 
 </td>
          </tr>
          </table>              
  
             
            </CommandItemTemplate>
             
<CommandItemSettings ExportToPdfText="Export to PDF"></CommandItemSettings>
 
<RowIndicatorColumn Visible="false" FilterControlAltText="Filter RowIndicator column"></RowIndicatorColumn>
 
<ExpandCollapseColumn Visible="false" FilterControlAltText="Filter ExpandColumn column"></ExpandCollapseColumn>
     
    <Columns>
     
                    <telerik:GridBoundColumn DataField="TransactionID"
            FilterControlAltText="Filter TransactionID column" HeaderText="TransactionID"
            SortExpression="TransactionID" UniqueName="TransactionID" DataType="System.Int32" ReadOnly="True" Visible="false">
        </telerik:GridBoundColumn>
        <telerik:GridBoundColumn UniqueName="MemberID" HeaderText="Member" DataField="MemberID" AllowFiltering="false" showfiltericon="false"  CurrentFilterFunction="NoFilter">
 
         
</telerik:GridBoundColumn>
<telerik:GridBoundColumn UniqueName="CPDistributorID" HeaderText="Distributor" DataField="CPDistributorID" AllowFiltering="false" showfiltericon="false"  CurrentFilterFunction="NoFilter">
        
</telerik:GridBoundColumn>
    </Columns>
    <EditFormSettings EditFormType="Template" >
                    <FormTemplate>
                     <div><br />
                      
                    
                      
                        <table width="920px" cellspacing="0" cellpadding="0">
                          <tr valign="top">
                            <td width="200px"><asp:Label ID="lblCompanyName" runat="server" Text="Member" Font-Bold="true"></asp:Label></td>
                            <td width="220px"><asp:Label ID="lblShipTop" runat="server" Text="Ship To" Font-Bold="true"></asp:Label></td>
                            <td width="498px"><asp:Label ID="lblPurchaseDate" runat="server" Text="Purchase Date" Font-Bold="true"></asp:Label></td>
                          </tr>
                          <tr valign="top">
                            <td width="200px">                            <telerik:RadComboBox ID="ddlMember" runat="server" AppendDataBoundItems="true" AutoPostBack="false"
                                                        EmptyMessage="Select..." DataSourceID="dsMembers" DataTextField="CompanyName"  DataValueField="MemberID" SelectedValue='<%# Bind("MemberID") %>' MarkFirstMatch="true" DropDownWidth="400px" HighlightTemplatedItems="true" Width="190px" Height="250px"  ClientEvents-OnKeyPress="KeyPressed" EnableLoadOnDemand="true" OnClientSelectedIndexChanging="LoadShipTo"  >
                            <HeaderTemplate>
                                                            <ul>
                                                                <li class="colCompanyName">Member</li>
                                                                <li class="colCPMember">CP Member</li>                                                               
                                                             </ul>
                                                             
                                                        </HeaderTemplate>
                                                        <ItemTemplate>
                                                            <ul>
                                                                <li class="colCompanyName"><%# Eval("CompanyName")%></li>
                                                                <li class="colCPMember" ><%# Eval("CPMember")%></li>
                                                            </ul>
                                                        </ItemTemplate>
                             
                            </telerik:RadComboBox></td>
                            <td width="220px">
                                <telerik:RadComboBox ID="ddlShipTo" runat="server"
                                datatextfield="ShipTo" DataValueField="ShipToID"
                                MarkFirstMatch="true" DropDownWidth="200px" HighlightTemplatedItems="true" Width="200px" EnableLoadOnDemand="true"  OnClientItemsRequested="ShipToLoaded"
        OnItemsRequested="ddlShipTo_ItemsRequested"  ClientEvents-OnKeyPress="KeyPressed" ></telerik:RadComboBox>
 
 
                            </td>
                <td width="400px"><telerik:RadDatePicker ID="txtPurchaseDate" runat="server"  ClientEvents-OnKeyPress="KeyPressed" Width="140px"   AutoPostBack="false"
                        DateInput-EmptyMessage="" MinDate="01/01/1000" MaxDate="01/01/3000"  dbSelectedDate='<%# Bind("PurchaseDate") %> '>
                        <Calendar ID="Calendar1" runat="server"  ClientEvents-OnKeyPress="KeyPressed">
                            <SpecialDays>
                                <telerik:RadCalendarDay Repeatable="Today" ItemStyle-CssClass="rcToday" />
                            </SpecialDays>
                        </Calendar>
                    </telerik:RadDatePicker></td>
                          </tr>
                          </table>
                                                          <table width="920px" border="0" cellpadding="1" cellspacing="0">
                                    <tr>
                                        <td width="180px" align="left"><asp:Label ID="Label8" runat="server" Text="Distributor" Font-Bold="true"></asp:Label></td>
                                        <td width="100px" align="left"><asp:Label ID="Label9" runat="server" Text="Invoice #" Font-Bold="true"></asp:Label></td>
                                        <td width="175px" align="left"><asp:Label ID="Label16" runat="server" Text="Product" Font-Bold="true"></asp:Label></td>
                                        <td width="75px" align="left"><asp:Label ID="Label17" runat="server" Text="Size" Font-Bold="true"></asp:Label></td>
                                        <td width="150px" align="left"><asp:Label ID="Label18" runat="server" Text="Manufacturer" Font-Bold="true"></asp:Label></td>
                                        <td  width="75px" align="left"><asp:Label ID="Label19" runat="server" Text="Quantity" Font-Bold="true"></asp:Label></td>
                                        <td  width="75px" align="left"><asp:Label ID="Label20" runat="server" Text="Price" Font-Bold="true"></asp:Label></td>
                                        <td  width="74px" align="left"><asp:Label ID="Label21" runat="server" Text="Extension" Font-Bold="true"></asp:Label></td>
                                    </tr>
                                                           
                                             <tr>
                                        <td width="180px" align="left"><telerik:RadComboBox ID="ddlDistributors" runat="server" AppendDataBoundItems="false" AutoPostBack="false"
                                                        EmptyMessage="Select..." DataSourceID="dsDistributors" DataTextField="DistributorName"  DataValueField="CPDistributorID" SelectedValue='<%# Bind("CPDistributorID") %>' MarkFirstMatch="true" DropDownWidth="200px" HighlightTemplatedItems="true" Width="170px" Height="250px"   ClientEvents-OnKeyPress="KeyPressed" ></telerik:RadComboBox>
                                        </td>
                                        <td width="100px" align="left">
                                            <telerik:RadTextBox ID="txtInvoiceNumber" Text='<%# Bind("InvoiceNumber") %>' runat="server" width="90px"></telerik:RadTextBox>
                                        </td>
                                        <td width="175px" align="left"><telerik:RadComboBox ID="ddlProduct" runat="server" EnableLoadOnDemand="true" DataTextField="Product"
                                         OnItemsRequested="ddlProduct_ItemsRequested" DataValueField="CPProductID" AutoPostBack="false" HighlightTemplatedItems="true" Width="170px" Height="250px"  DropDownWidth="500px"   ClientEvents-OnKeyPress="KeyPressed"  markfirstmatch="true" Filter="contains">
                                                        <HeaderTemplate>
                                                            <ul>
                                                                <li class="colProductName">Product Name</li>
                                                                <li class="colSize">Pkg Size</li>                                                               
                                                                <li class="colSuppleer">Manufacturer</li>                                                               
                                                             </ul>
                                                             
                                                        </HeaderTemplate>
                                                        <ItemTemplate>
                                                            <ul>
                                                                <li class="colProductName"> <%# DataBinder.Eval(Container, "Text")%></li>
                                                                <li class="colSize" > <%# DataBinder.Eval(Container, "Attributes['Size']")%></li>
                                                                <li class="colSuppleer"> <%# DataBinder.Eval(Container, "Attributes['SupplierName']")%></li>  
                                                            </ul>
                                                        </ItemTemplate>
                                                        </telerik:RadComboBox></td>
                                        <td width="75px" align="left"><telerik:RadTextBox ID="txtSize" Text='<%# Eval("Size") %>' runat="server" ReadOnly="true" Width="70px" ></telerik:RadTextBox></td>
                                        <td width="150px" align="left"><telerik:RadTextBox ID="txtManufacturer" Text='<%# Eval("SupplierName") %>' runat="server" ReadOnly="true" Width="145px"></telerik:RadTextBox></td>
                                        <td width="75px" align="left"><telerik:RadNumericTextBox incrementsettings-interceptarrowskeys="false" incrementsettings-interceptmousewheel="false"  ID="txtQuantity" NumberFormat-DecimalDigits="3"  runat="server" Type="number" width="55px" NumberFormat-DecimalSeparator="." NumberFormat-GroupSeparator="" invalidstyleduration="100" Dbvalue='<%# Bind("Quantity") %>'  EmptyMessage="0.000" ><EmptyMessageStyle Width="55px" /><ReadOnlyStyle Width="55px" /> </telerik:RadNumericTextBox></td>
                                        <td width="75px" align="left"><telerik:RadNumericTextBox incrementsettings-interceptarrowskeys="false" incrementsettings-interceptmousewheel="false"  ID="txtPrice" runat="server" Type="currency" width="65px" EmptyMessageStyle-Width="65px" MinValue="0.000" NumberFormat-DecimalSeparator="."  Dbvalue='<%# Bind("Price") %>' NumberFormat-DecimalDigits="3" EmptyMessage="0.000" ><EmptyMessageStyle Width="55px" /><ReadOnlyStyle Width="55px" /></telerik:RadNumericTextBox></td>
                                        <td width="74px" align="left"><telerik:RadNumericTextBox incrementsettings-interceptarrowskeys="false" incrementsettings-interceptmousewheel="false"  ID="txtExtension" runat="server" Type="currency" width="65px" EmptyMessageStyle-Width="65px" NumberFormat-DecimalSeparator="."  Dbvalue='<%# Bind("Extension") %>' NumberFormat-DecimalDigits="2"  NumberFormat-NegativePattern="$- n" ><EmptyMessageStyle Width="55px" /><ReadOnlyStyle Width="55px" /></telerik:RadNumericTextBox></td>
                                    </tr>
                                </table>
 
                        
                                                 <asp:Label id="lblMissing" runat="server" Text="All fields required except Extension." ForeColor="Red" Font-Bold="true" Visible="false"></asp:Label><br /></div>
                    </FormTemplate>
</EditFormSettings>
 
</MasterTableView>
        <ClientSettings AllowKeyboardNavigation="false">
         
         <ClientEvents OnKeyPress="CatchKeyPress" OnCommand="gridCommand" ></ClientEvents>
          
                         <Selecting AllowRowSelect="true" />
                                              <Scrolling AllowScroll="true"  UseStaticHeaders="true" />
        </ClientSettings>
        </telerik:RadGrid>
 
 
 
            <asp:SqlDataSource ID="SqlDataSource1" runat="server"
            ConnectionString="<%$ ConnectionStrings:csPrairielandAg %>"
            ProviderName="<%$ ConnectionStrings:csPrairielandAg.ProviderName %>"
 
            UpdateCommand="UPDATE dbo.tblCropProtectionTransactionsTEMP SET MemberID = @MemberID, ShipToID = @ShipToID, PurchaseDate = @PurchaseDate, CPDistributorID = @CPDistributorID, InvoiceNumber = @InvoiceNumber, CPProductID = @CPProductID, Quantity = @Quantity, Price = @Price, Extension = @Extension where TransactionID = @TransactionID"
             
            InsertCommand="INSERT INTO dbo.tblCropProtectionTransactions(MemberID, ShipToID, CPDistributorID, PurchaseDate, InvoiceNumber, CPProductID, Quantity, Price, Extension, NetPricing, DPS) VALUES (@MemberID, @ShipToID, @CPDistributorID, @PurchaseDate, @InvoiceNumber, @CPProductID, @Quantity, @Price, @Extension, @NetPricing, @DPS)">
                <InsertParameters>
                    <asp:Parameter Name="MemberID" />
                    <asp:Parameter Name="ShipToID" />
                    <asp:Parameter Name="CPDistributorID" />
                    <asp:Parameter Name="PurchaseDate" />
                    <asp:Parameter Name="InvoiceNumber" />
                    <asp:Parameter Name="CPProductID" />
                    <asp:Parameter Name="Quantity" />
                    <asp:Parameter Name="Price" />
                    <asp:Parameter Name="Extension" />
                    <asp:Parameter Name="NetPricing" DefaultValue="0" />
                    <asp:Parameter Name="DPS"  DefaultValue="0" />
                </InsertParameters>
            <UpdateParameters>
                <asp:Parameter Name="TransactionID" />
                <asp:Parameter Name="MemberID" />
                <asp:Parameter Name="ShipToID" />
                <asp:Parameter Name="PurchaseDate" />
                <asp:Parameter Name="CPDistributorID" />
                <asp:Parameter Name="InvoiceNumber" />
                <asp:Parameter Name="CPProductID" />
                <asp:Parameter Name="Quantity" />
                <asp:Parameter Name="Price" />
                <asp:Parameter Name="Extension" />
            </UpdateParameters>
        </asp:SqlDataSource>
 
            <asp:SqlDataSource ID="dsSupplier" runat="server"
            ConnectionString="<%$ ConnectionStrings:csPrairielandAg %>"
            ProviderName="<%$ ConnectionStrings:csPrairielandAg.ProviderName %>"
            SelectCommand="SELECT CPSupplierID, SupplierName FROM dbo.tblCropProtectionSuppliers" >
        </asp:SqlDataSource>
 <asp:SqlDataSource ID="dsProducts" runat="server"
            ConnectionString="<%$ ConnectionStrings:csPrairielandAg %>"
            ProviderName="<%$ ConnectionStrings:csPrairielandAg.ProviderName %>"
            SelectCommand="SELECT CPProductID,Product,Size,SupplierName from tblCropProtectionProducts a join tblCropProtectionSuppliers b on a.CPSupplierID = b.CPSupplierID
order by PRoduct,Size,SupplierName" >
        </asp:SqlDataSource>
 <asp:SqlDataSource ID="dsDistributors" runat="server"
            ConnectionString="<%$ ConnectionStrings:csPrairielandAg %>"
            ProviderName="<%$ ConnectionStrings:csPrairielandAg.ProviderName %>"
            SelectCommand="select CPDistributorID, DistributorName from tblCropProtectionDistributors order by DistributorName" >
 
        </asp:SqlDataSource>
            <asp:SqlDataSource ID="dsMembers" runat="server"
            ConnectionString="<%$ ConnectionStrings:csPrairielandAg %>"
            ProviderName="<%$ ConnectionStrings:csPrairielandAg.ProviderName %>"
            SelectCommand="SELECT distinct tblMembers.MemberId, tblMembers.CompanyName, tblMembers.Email, case [CropProtection] when 1 then 'Yes' when 0 then 'No' end AS [CPMember] FROM tblMembers ORDER BY tblMembers.CompanyName" >
 
        </asp:SqlDataSource>
                    <asp:SqlDataSource ID="dsShipTo" runat="server"
            ConnectionString="<%$ ConnectionStrings:csPrairielandAg %>"
            ProviderName="<%$ ConnectionStrings:csPrairielandAg.ProviderName %>"
            SelectCommand="SELECT ShipToId, ShipTo from tblMemberShipTo where MemberID = @MemberID order by IsDefault desc, ShipTo asc">
            <SelectParameters>
               <asp:Parameter Name="MemberID" />
            </SelectParameters>                  
             
 
        </asp:SqlDataSource>
 
        <br />
            </div>
 
 
</asp:Content>


aspx.vb:
Imports System
Imports System.Data
Imports System.Configuration
Imports System.Collections
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls
Imports Telerik.Web.UI
Imports System.Data.OleDb
Imports System.Data.SqlClient
Imports System.Collections.Generic
Imports System.Data.Common
Imports System.Diagnostics
Imports System.ComponentModel
Imports System.Web.SessionState
Imports System.Web.Mail
Imports System.Net.Mail
Imports System.Xml
Partial Public Class CP_TransactionsAdd
 
    Inherits System.Web.UI.Page
 
    Dim strMode As String = ""
    Dim strSelectCommand As String = ""
    Dim strInsertCommand As String = ""
    Dim strSQL As String = ""
    Dim total As Integer
    Dim msg As String = ""
    Dim member As MembershipUser = Membership.GetUser(User.Identity.Name)
    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
        ' RadGrid1.Enabled = True
        ' RadGrid1.Visible = True
        Session("Refresh") = "Yes"
        strSelectCommand = "select TransactionID, MemberID, ShipToID, PurchaseDate, CPDistributorID, InvoiceNumber, a.CPProductID,Product,Size,SupplierName, Quantity, Price, Extension, Comments from tblCropProtectionTransactionsTEMP a left join tblCropProtectionProducts b on a.CPProductID = b.CPProductID left join tblCropProtectionSuppliers c on b.CPSupplierID = c.CPSupplierID where UserName = '" & member.UserName & "' order by TransactionID asc"
        SqlDataSource1.SelectCommand = strSelectCommand
        If (Not Page.IsPostBack) Then
            Try
                Using conn As New SqlConnection(ConnectionString)
                    Dim cmdInsert As New SqlCommand()
                    conn.Open()
                    cmdInsert.Connection = conn
                    cmdInsert.CommandType = CommandType.Text
                    cmdInsert.CommandText = "Delete from tblCropProtectionTransactionsTEMP where UserName = '" & member.UserName & "'"
                    cmdInsert.ExecuteNonQuery()
                End Using
                lblError.Visible = False
                msg = ""
            Catch exSQL As SqlException
                Select Case exSQL.Number
                    Case Else
                        lblError.Text = exSQL.Message.ToString() & " If this error persists, contact EERC Research Information Systems for help."
                        lblError.Visible = True
                End Select
 
            Catch ex As Exception
                lblError.Text = ex.Message.ToString() & " If this error persists, contact EERC Research Information Systems for help."
                '                lblError.visible = true
            End Try
        End If
    End Sub
 
    Protected Sub RadAjaxManager1_AjaxRequest(sender As Object, e As AjaxRequestEventArgs)
        '        RadGrid1.Items.Item(1).FireCommandEvent("Update", String.Empty)
    End Sub
 
 
    Protected Sub RadGrid1_ItemCommand(sender As Object, e As Telerik.Web.UI.GridCommandEventArgs) Handles RadGrid1.ItemCommand
        If e.CommandName = "RefreshGrid" Then
            strMode = "Refresh"
            e.Item.OwnerTableView.Rebind()
        ElseIf e.CommandName = "SaveChanges" Then
            RadGrid1_UpdateCommand(sender, e)
            'e.Item.OwnerTableView.Rebind()
            strMode = "Save"
        ElseIf e.CommandName = "CancelChanges" Then
            strMode = "Cancel"
 
            For Each column As GridColumn In RadGrid1.MasterTableView.Columns
                column.CurrentFilterFunction = GridKnownFunction.NoFilter
                column.CurrentFilterValue = String.Empty
            Next
            RadGrid1.MasterTableView.FilterExpression = String.Empty
            e.Item.OwnerTableView.Rebind()
        ElseIf e.CommandName = "Sort" Then
            strMode = "Sort"
        ElseIf e.CommandName = "Page" Then
            strMode = "Page"
        ElseIf e.CommandName = "ChangePageSize" Then
            RadGrid1.EditIndexes.Clear()
        End If
        If e.CommandName = "DeleteRow" Then
            Dim intTransactionID = e.Item.OwnerTableView.DataKeyValues(e.Item.ItemIndex)("CPProductID").ToString
            Try
                Dim deleteQuery As String = "Delete from tblCropProtectionProducts where TransactionID='" & intTransactionID & "'"
                Dim strConn As String = ConfigurationManager.ConnectionStrings("csPrairielandAg").ConnectionString
                Using connection As New SqlConnection(strConn)
                    connection.Open()
                    Using Command As New SqlCommand(deleteQuery, connection)
                        Command.CommandType = Data.CommandType.Text
                        Command.CommandText = deleteQuery
                        Command.ExecuteNonQuery()
                        SetMessage("Transaction deleted")
                    End Using
                    connection.Close()
                End Using
                RadGrid1.Rebind()
            Catch ex As Exception
                If InStr(ex.Message, "The DELETE statement conflicted with the REFERENCE constraint", CompareMethod.Text) > 0 Then
                    SetMessage("Cannot delete this Transaction.")
                Else
                    SetMessage(ex.Message)
                End If
 
 
            End Try
        End If
 
 
    End Sub
 
    Protected Sub RadGrid1_PageIndexChanged(sender As Object, e As Telerik.Web.UI.GridPageChangedEventArgs) Handles RadGrid1.PageIndexChanged
        If RadGrid1.Items.Item(1).IsInEditMode = True Then
            e.Item.FireCommandEvent("Update", String.Empty)
        End If
 
    End Sub
 
    Protected Sub RadGrid1_PreRender(sender As Object, e As System.EventArgs) Handles RadGrid1.PreRender
        For i As Integer = 0 To RadGrid1.Items.Count
            RadGrid1.EditIndexes.Add(i)
        Next
        RadGrid1.Rebind()
        For Each item As GridDataItem In RadGrid1.MasterTableView.Items
            item.Display = False
        Next
    End Sub
 
    Protected Sub RadGrid1_UpdateCommand(sender As Object, e As Telerik.Web.UI.GridCommandEventArgs) Handles RadGrid1.UpdateCommand
 
        If RadGrid1.EditItems.Count > 0 Then
            For Each item As GridDataItem In RadGrid1.EditItems
                Dim dataItem As GridEditFormItem = DirectCast(item.EditFormItem, GridEditFormItem)
 
                '      Dim newValues As New Hashtable()
                'Dim eeditedItem As GridEditableItem = TryCast(e.Item, GridEditableItem)
                Dim intTransactionID As Integer = dataItem.OwnerTableView.DataKeyValues(dataItem.ItemIndex)("TransactionID")
                Dim test As RadComboBox = TryCast(dataItem.OwnerTableView.FindControl("ddlProduct"), RadComboBox)
                '     RadGrid1.MasterTableView.ExtractValuesFromItem(newValues, dataItem)
                Dim productCombo As RadComboBox = TryCast(dataItem.FindControl("ddlProduct"), RadComboBox)
                Dim memberCombo As RadComboBox = TryCast(dataItem.FindControl("ddlMember"), RadComboBox)
                Dim shiptoCombo As RadComboBox = TryCast(dataItem.FindControl("ddlShipTo"), RadComboBox)
                Dim txtPurchaseDate As RadDatePicker = TryCast(dataItem.FindControl("txtPurchaseDate"), RadDatePicker)
                Dim ddlDistributors As RadComboBox = TryCast(dataItem.FindControl("ddlDistributors"), RadComboBox)
                Dim txtInvoiceNumber As RadTextBox = TryCast(dataItem.FindControl("txtInvoiceNumber"), RadTextBox)
                Dim txtQuantity As RadNumericTextBox = TryCast(dataItem.FindControl("txtQuantity"), RadNumericTextBox)
                Dim txtPrice As RadNumericTextBox = TryCast(dataItem.FindControl("txtPrice"), RadNumericTextBox)
                Dim txtExtension As RadNumericTextBox = TryCast(dataItem.FindControl("txtExtension"), RadNumericTextBox)
                SqlDataSource1.UpdateParameters("TransactionID").DefaultValue = intTransactionID
                SqlDataSource1.UpdateParameters("MemberID").DefaultValue = memberCombo.SelectedValue
                SqlDataSource1.UpdateParameters("ShipToID").DefaultValue = shiptoCombo.SelectedValue
                SqlDataSource1.UpdateParameters("CPDistributorID").DefaultValue = ddlDistributors.SelectedValue
                SqlDataSource1.UpdateParameters("PurchaseDate").DefaultValue = txtPurchaseDate.DbSelectedDate
                SqlDataSource1.UpdateParameters("InvoiceNumber").DefaultValue = txtInvoiceNumber.Text
                SqlDataSource1.UpdateParameters("CPProductID").DefaultValue = productCombo.SelectedValue
                SqlDataSource1.UpdateParameters("Quantity").DefaultValue = txtQuantity.Text
                SqlDataSource1.UpdateParameters("Price").DefaultValue = txtPrice.Text
                SqlDataSource1.UpdateParameters("Extension").DefaultValue = txtExtension.Text
 
 
                Try
                    SqlDataSource1.Update()
                    lblError.Visible = False
                    '    e.Canceled = True
                    '  RadGrid1.EditIndexes.Clear()
                Catch ex As Exception
                    SetMessage(Server.HtmlEncode("Unable to update Transaction. Reason: " + ex.Message).Replace("'", "'").Replace(vbCrLf, "<br />"))
                End Try
            Next
 
        Else
            Exit Sub
        End If
 
    End Sub
    Private Sub SetMessage(ByVal message As String)
        lblError.Text = String.Format("<span style='color:red'>{0}</span>", message)
        lblError.Visible = True
    End Sub
    Protected Sub ddlProduct_ItemDataBound(o As Object, e As RadComboBoxItemEventArgs)
        Dim row As DataRowView = TryCast(e.Item.DataItem, DataRowView)
        Dim selectedItem As New RadComboBoxItem()
        ' selectedItem.Text = DirectCast(e.Item.DataItem, DataRowView)("Product").ToString()
        selectedItem.Value = DirectCast(e.Item.DataItem, DataRowView)("CPProductID").ToString()
        selectedItem.Attributes.Add("Size", DirectCast(e.Item.DataItem, DataRowView)("Size").ToString())
        selectedItem.Attributes.Add("SupplierName", DirectCast(e.Item.DataItem, DataRowView)("SupplierName").ToString())
        o.Items.Add(selectedItem)
 
        selectedItem.DataBind()
 
    End Sub
    Protected Sub ddlProduct_ItemsRequested(ByVal o As Object, ByVal e As RadComboBoxItemsRequestedEventArgs)
        Dim sql As String = dsProducts.SelectCommand.ToString
        Dim connection As New SqlConnection(ConfigurationManager.ConnectionStrings("csPrairielandAg").ConnectionString)
        Dim adapter As New SqlDataAdapter(sql, connection)
        Dim dt As New DataTable()
        adapter.Fill(dt)
        Dim comboBox As RadComboBox = DirectCast(o, RadComboBox)
        comboBox.Items.Clear()
        For Each row As DataRow In dt.Rows
            Dim item As New RadComboBoxItem()
            item.Text = row("Product").ToString()
            item.Value = row("CPProductID").ToString()
            'item.Attributes.Add("Product", row("Product").ToString())
            item.Attributes.Add("Size", row("Size").ToString())
            item.Attributes.Add("SupplierName", row("SupplierName").ToString())
 
            comboBox.Items.Add(item)
 
            item.DataBind()
        Next
 
    End Sub
    Protected Sub OnItemDataBoundHandler(ByVal sender As Object, ByVal e As GridItemEventArgs)
        If e.Item.IsInEditMode Then
            Dim item As GridEditableItem = DirectCast(e.Item, GridEditableItem)
 
            If Not (TypeOf e.Item Is IGridInsertItem) Then
                Dim combo As RadComboBox = DirectCast(item.FindControl("ddlProduct"), RadComboBox)
 
                Dim selectedItem As New RadComboBoxItem()
                If DirectCast(e.Item.DataItem, DataRowView)("Product").ToString() <> "" Then
                    selectedItem.Text = DirectCast(e.Item.DataItem, DataRowView)("Product").ToString()
                    selectedItem.Value = DirectCast(e.Item.DataItem, DataRowView)("CPProductID").ToString()
                    selectedItem.Attributes.Add("Size", DirectCast(e.Item.DataItem, DataRowView)("Size").ToString())
                    selectedItem.Attributes.Add("SupplierName", DirectCast(e.Item.DataItem, DataRowView)("SupplierName").ToString())
 
                    combo.Items.Add(selectedItem)
 
                    selectedItem.DataBind()
 
                End If
                ' Session("CPProductID") = selectedItem.Value
            End If
        End If
    End Sub
 
    Protected Function LoadShipTo(MemberID As String) As DataTable
        Dim connection As New SqlConnection(ConfigurationManager.ConnectionStrings("csPrairielandAg").ConnectionString)
 
        'select a country based on the continentID
        Dim adapter As New SqlDataAdapter("SELECT ShipToId, ShipTo from tblMemberShipTo where MemberId=@MemberID order by IsDefault desc, ShipTo asc", connection)
        adapter.SelectCommand.Parameters.AddWithValue("@MemberID", MemberID)
 
        Dim dt As New DataTable()
        adapter.Fill(dt)
 
        Return dt
    End Function
 
    Protected Sub RadGrid1_ItemDataBound(sender As Object, e As Telerik.Web.UI.GridItemEventArgs) Handles RadGrid1.ItemDataBound
        If TypeOf e.Item Is GridEditableItem AndAlso e.Item.IsInEditMode Then
            Dim editedItem As GridEditableItem = TryCast(e.Item, GridEditableItem)
 
 
            Dim dataSourceRow As DataRowView = DirectCast(e.Item.DataItem, DataRowView)
            Dim memberCombo As RadComboBox = TryCast(editedItem.FindControl("ddlMember"), RadComboBox)
            Dim shiptoCombo As RadComboBox = TryCast(editedItem.FindControl("ddlShipto"), RadComboBox)
            shiptoCombo.DataSource = LoadShipTo(memberCombo.SelectedValue)
            shiptoCombo.DataBind()
            shiptoCombo.SelectedValue = dataSourceRow("ShipToID").ToString()
 
            Dim productCombo As RadComboBox = TryCast(editedItem.FindControl("ddlProduct"), RadComboBox)
 
            Dim txtSize As RadTextBox = TryCast(editedItem.FindControl("txtSize"), RadTextBox)
            Dim txtManufacturer As RadTextBox = TryCast(editedItem.FindControl("txtManufacturer"), RadTextBox)
            If productCombo.SelectedValue <> "" Then
                txtSize.Text = productCombo.SelectedItem.Attributes("Size").ToString
                txtManufacturer.Text = productCombo.SelectedItem.Attributes("SupplierName").ToString
            End If
 
        End If
        If TypeOf e.Item Is GridPagerItem Then
            Dim pager As GridPagerItem = DirectCast(e.Item, GridPagerItem)
            Dim PageSizeComboBox As RadComboBox = DirectCast(pager.FindControl("PageSizeComboBox"), RadComboBox)
            PageSizeComboBox.Visible = False
            Dim changePageSizelbl As Label = DirectCast(pager.FindControl("ChangePageSizeLabel"), Label)
            changePageSizelbl.Visible = False
        End If
 
    End Sub
 
 
 
    Protected Sub RadGrid1_ItemCreated(sender As Object, e As Telerik.Web.UI.GridItemEventArgs) Handles RadGrid1.ItemCreated
 
        If TypeOf e.Item Is GridEditableItem AndAlso e.Item.IsInEditMode Then
            Dim editedItem As GridEditableItem = TryCast(e.Item, GridEditableItem)
 
            Dim productCombo As RadComboBox = TryCast(editedItem.FindControl("ddlProduct"), RadComboBox)
            productCombo.OnClientSelectedIndexChanged() = "function (button,args){Selected('" & editedItem.ItemIndex & "',args);}"
 
            Dim memberCombo As RadComboBox = TryCast(editedItem.FindControl("ddlMember"), RadComboBox)
            Dim shiptoCombo As RadComboBox = TryCast(editedItem.FindControl("ddlShipTo"), RadComboBox)
            Dim txtPurchaseDate As RadDatePicker = TryCast(editedItem.FindControl("txtPurchaseDate"), RadDatePicker)
            Dim ddlDistributors As RadComboBox = TryCast(editedItem.FindControl("ddlDistributors"), RadComboBox)
            Dim txtInvoiceNumber As RadTextBox = TryCast(editedItem.FindControl("txtInvoiceNumber"), RadTextBox)
            Dim txtQuantity As RadNumericTextBox = TryCast(editedItem.FindControl("txtQuantity"), RadNumericTextBox)
            Dim txtPrice As RadNumericTextBox = TryCast(editedItem.FindControl("txtPrice"), RadNumericTextBox)
            Dim txtExtension As RadNumericTextBox = TryCast(editedItem.FindControl("txtExtension"), RadNumericTextBox)
            memberCombo.Attributes.Add("ddItemIndex", editedItem.ItemIndex)
            memberCombo.Attributes.Add("ddClientID", shiptoCombo.ClientID)
            productCombo.Attributes.Add("onchange", "return updateEdit();")
            memberCombo.Attributes.Add("onchange", "return updateEdit();")
            shiptoCombo.Attributes.Add("onchange", "return updateEdit();")
            txtPurchaseDate.Attributes.Add("onchange", "return updateEdit();")
            ddlDistributors.Attributes.Add("onchange", "return updateEdit();")
            txtInvoiceNumber.Attributes.Add("onchange", "return updateEdit();")
            txtQuantity.Attributes.Add("onchange", "return updateEdit();")
            txtQuantity.ClientEvents.OnValueChanged() = "function (button,args){UpdateExtension('" & editedItem.ItemIndex & "','" & txtExtension.ClientID & "',args);}"
            txtPrice.Attributes.Add("onchange", "return updateEdit();")
            txtPrice.ClientEvents.OnValueChanged() = "function (button,args){UpdateExtension('" & editedItem.ItemIndex & "','" & txtExtension.ClientID & "',args);}"
 
        End If
    End Sub
    Protected Sub ddlShipTo_ItemsRequested(ByVal o As Object, ByVal e As RadComboBoxItemsRequestedEventArgs)
        o.DataTextField = "ShipTo"
        o.DataValueField = "ShipToId"
        o.DataSource = LoadShipTo(e.Text)
        o.DataBind()
    End Sub
 
 
    Protected Sub RadGrid1_NeedDataSource(sender As Object, e As Telerik.Web.UI.GridNeedDataSourceEventArgs) Handles RadGrid1.NeedDataSource
 
        RadGrid1.DataSource = SqlDataSource1
        ' Session("Refresh") = "Yes"
    End Sub
    Public ReadOnly Property ConnectionString() As String
        Get
            Return ConfigurationManager.ConnectionStrings("csPrairielandAg").ConnectionString
        End Get
    End Property
    Protected Sub btnGrid_Click(sender As Object, e As System.EventArgs) Handles btnGrid.Click
        If ddlDistributors.SelectedValue = "" Or txtRows.Text = "" Then
            SetMessage("Please choose a distributor and # of Rows")
            Session("Refresh") = "No"
            Exit Sub
 
        End If
 
        Dim strSQL As String
        Dim msg As String = ""
        lblError.Text = ""
        Dim member As MembershipUser = Membership.GetUser(User.Identity.Name)
        Try
            Using conn As New SqlConnection(ConnectionString)
                Dim cmdInsert As New SqlCommand()
                conn.Open()
                cmdInsert.Connection = conn
                For i As Integer = 1 To txtRows.Text
                    strSQL = "INSERT INTO tblCropProtectionTransactionsTEMP (CPDistributorID,UserName) values(" & ddlDistributors.SelectedValue & ",'" & member.UserName & "')"
                    cmdInsert.CommandText = strSQL
                    cmdInsert.ExecuteNonQuery()
                Next
            End Using
            msg = ""
            lblError.Visible = False
            Session("Refresh") = "Yes"
            RadGrid1.Rebind()
        Catch exSQL As SqlException
            Select Case exSQL.Number
                Case Else
                    lblError.Text = exSQL.Message.ToString() & " If this error persists, contact EERC Research Information Systems for help."
                    lblError.Visible = True
            End Select
 
        Catch ex As Exception
            lblError.Text = ex.Message.ToString() & " If this error persists, contact EERC Research Information Systems for help."
            lblError.Visible = True
        End Try
 
    End Sub
End Class

1 Answer, 1 is accepted

Sort by
0
Pavlina
Telerik team
answered on 11 Dec 2012, 09:56 PM
Hi,

Can you send us a live url where the described issues can be observed? Also provide step by step instructions how to reproduce these problems. We will inspect the grid locally and will get back to you with additional information.

Regards,
Pavlina
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.
Tags
Grid
Asked by
ADT
Top achievements
Rank 1
Answers by
Pavlina
Telerik team
Share this question
or