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

radgrid edit form template - access controls within

2 Answers 567 Views
Grid
This is a migrated thread and some comments may be shown as answers.
ADT
Top achievements
Rank 1
ADT asked on 28 Nov 2012, 09:06 PM
Hello all,

I have a radgrid which uses edit form templates. The grid has too many fields so I cannot use in-line edit mode (which I have a much better understanding of ) and I need to use edit form template instead. Basically when the grid opens I set every row to edit mode then I hide the databound columns. The only reason I actually have them is so I can set filters at the top of the Grid. My problem is that I need to change some textboxes in a specific "record" without doing a postback but I cannot seem to figure out how to access these textbox's.
I have a couple drop downs that when they are changed I need them to change textboxes to other values. I believe once I figure this out I will be able to figure out how to loop through all the data for my saves. Although some code for the save/add new buttons are there and also in the .vb code for update, I haven't programmed these yet so they can be ignored as it is not my concern at the moment.

Can anyone steer me in the right direction or have any insight? I will paste all my code below
Also, on render I am hiding the item template and showing only the edit template with item.Display = false. Is this the proper way to go about this as well?

I appreciate any help or direction.

Thanks,
ASPx code:
<%@ Page Title="" Language="VB" MasterPageFile="~/MasterNoBanner.master" AutoEventWireup="false" CodeFile="CropProtectionTransactions.aspx.vb" Inherits="CP_Transactions" %>
 
<%@ Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" %>
 
<asp:Content ID="Content1" ContentPlaceHolderID="cphBodyText" Runat="Server">
    <div style="width: 980px; 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 ddlProductChanged(sender, eventArgs) {
                    //This is where I need to update the other two fields
                                        
               }
 
 
               </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="Label1" />
                </UpdatedControls>
            </telerik:AjaxSetting>
 
 
        </AjaxSettings>
    </telerik:RadAjaxManager>
    <telerik:RadAjaxLoadingPanel ID="RadAjaxLoadingPanel1" runat="server" Height="16px"
            Width="16px" />
 
<asp:Label id="Label1" runat="server" Text="asdf" Visible="false"></asp:Label>
 
        <telerik:RadGrid ID="RadGrid1" DataSourceID="SqlDataSource1"
            ShowStatusBar="True"  AllowFilteringByColumn="True"
            AllowSorting="True"   GridLines="None"  runat="server"
            AutoGenerateColumns="False" CellSpacing="0" AllowMultiRowEdit="True"
            Height="800px" Width="98%" PageSize="3"  AllowPaging="True">
            <ClientSettings>
             
<Selecting AllowRowSelect="True"></Selecting>
 
<ClientEvents OnKeyPress="CatchKeyPress"></ClientEvents>
 
            <Scrolling AllowScroll="true" UseStaticHeaders="true"></Scrolling>
        </ClientSettings>
         
 
            <MasterTableView EditMode="EditForms" DataKeyNames="TransactionID" DataSourceID="SqlDataSource1" CommandItemDisplay="Top"  PagerStyle-AlwaysVisible="true" InsertItemDisplay="Top" InsertItemPageIndexAction="ShowItemOnCurrentPage"  >
             
                <CommandItemTemplate>
                 
          <table width="100%">
          <tr>
            <td align="right"><asp:LinkButton ID="btnInsertProduct" OnClientClick="gridCommandCustom('AddRecord')" runat="server" CommandName="InsertProduct" Visible="true"><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:GridDropDownColumn UniqueName="MemberID" SortExpression="MemberID" HeaderText="Company Name" DataSourceID="dsMembers" DataField="MemberID"
                  ListTextField="CompanyName" ListValueField="MemberID" AllowAutomaticLoadOnDemand="false"  DropDownControlType="radcombobox" FilterControlWidth="150px" autopostbackonfilter="true" EmptyListItemText="Select ..."  showfiltericon="false" > <HeaderStyle Width="125px" /><ItemStyle Width="125px"  />
                                    <FilterTemplate>
                        <telerik:RadComboBox ID="RadComboBoxMembers" DataSourceID="dsMembers" DataTextField="CompanyName"
                            DataValueField="MemberID" Height="200px" AppendDataBoundItems="true" MarkFirstMatch="true" AllowCustomText="false" SelectedValue='<%# TryCast(Container,GridItem).OwnerTableView.GetColumn("MemberID").CurrentFilterValue %>'
                            runat="server" OnClientSelectedIndexChanged="MemberIndexChanged" Width="90%" DropDownWidth="350px">
                            <Items>
                                <telerik:RadComboBoxItem Text="All" />
                            </Items>
                        </telerik:RadComboBox>
                        <telerik:RadScriptBlock ID="RadScriptBlockMembers" runat="server">
                            <script type="text/javascript">
                                function MemberIndexChanged(sender, args) {
                                    var tableView = $find("<%# TryCast(Container,GridItem).OwnerTableView.ClientID %>");
                                    tableView.filter("MemberID", args.get_item().get_value(), "EqualTo");
                                }
                            </script>
                        </telerik:RadScriptBlock>
                    </FilterTemplate>
                   
                  </telerik:GridDropDownColumn>
                <telerik:GridTemplateColumn DataField="ShipTo" FilterControlAltText="Filter ShipTo column" HeaderText="Ship To" ShowFilterIcon="false"
        UniqueName="ShipTo" SortExpression="ShipTo" ItemStyle-Height="0px">
         
        </telerik:GridTemplateColumn>
                        <telerik:GridTemplateColumn DataField="PurchaseDate" FilterControlAltText="Filter PurchaseDate column" HeaderText="Purchase Date " ShowFilterIcon="false"
        UniqueName="PurchaseDate" SortExpression="PurchaseDate" ItemStyle-Height="0px">
         
        </telerik:GridTemplateColumn>
                          <telerik:GridTemplateColumn DataField="DistributorName" FilterControlAltText="Filter DistributorName column" HeaderText="Distributor Name" ShowFilterIcon="false"
        UniqueName="DistributorName" SortExpression="DistributorName" ItemStyle-Height="0px">
         
        </telerik:GridTemplateColumn>
                                <telerik:GridDropDownColumn UniqueName="CPProductID" SortExpression="CPProductID" HeaderText="Supplier" DataSourceID="dsProducts" DataField="CPProductID"
                  ListTextField="Product" ListValueField="CPProductID" AllowAutomaticLoadOnDemand="false"  DropDownControlType="radcombobox" FilterControlWidth="150px" autopostbackonfilter="true" EmptyListItemText="Select ..."  showfiltericon="false" > <HeaderStyle Width="225px" /><ItemStyle Width="225px"  />
                                    <FilterTemplate>
                        <telerik:RadComboBox ID="RadComboboxProduct" DataSourceID="dsProducts" DataTextField="Product"
                            DataValueField="CPProductID" Height="200px" AppendDataBoundItems="true" MarkFirstMatch="true" AllowCustomText="false" SelectedValue='<%# TryCast(Container,GridItem).OwnerTableView.GetColumn("CPProductID").CurrentFilterValue %>'
                            runat="server" OnClientSelectedIndexChanged="ProductIndexChanged">
                            <Items>
                                <telerik:RadComboBoxItem Text="All" />
                            </Items>
                        </telerik:RadComboBox>
                        <telerik:RadScriptBlock ID="RadScriptBlock1" runat="server">
                            <script type="text/javascript">
                                function ProductIndexChanged(sender, args) {
                                    var tableView = $find("<%# TryCast(Container,GridItem).OwnerTableView.ClientID %>");
                                    tableView.filter("CPProductID", args.get_item().get_value(), "EqualTo");
 
                                }
                            </script>
                        </telerik:RadScriptBlock>
                    </FilterTemplate>
                   
                  </telerik:GridDropDownColumn>
 
        
    </Columns>
    <EditFormSettings EditFormType="Template" >
                    <FormTemplate>
                     <div><br />
                        <table style="margin-left: 5px;" width="99%">
                          <tr valign="top">
                            <td width="150px"><asp:Label ID="lblCompanyName" runat="server" Text="Member" Font-Bold="true"></asp:Label></td>
                            <td width="120px"><asp:Label ID="lblShipTop" runat="server" Text="Ship To" Font-Bold="true"></asp:Label></td>
                            <td ><asp:Label ID="lblPurchaseDate" runat="server" Text="Purchase Date" Font-Bold="true"></asp:Label></td>
                          </tr>
                          <tr valign="top">
                            <td>                            <telerik:RadComboBox ID="ddlMember" runat="server" AppendDataBoundItems="true" AutoPostBack="true"
                                                        EmptyMessage="Select..." DataSourceID="dsMembers" DataTextField="CompanyName"  DataValueField="MemberID" SelectedValue='<%# Bind("MemberID") %>' MarkFirstMatch="true" DropDownWidth="400px" HighlightTemplatedItems="true" Width="200px" Height="250px" OnSelectedIndexChanged="ddlMember_SelectedIndexChanged"  ClientEvents-OnKeyPress="KeyPressed" EnableLoadOnDemand="false" >
                            <HeaderTemplate>
                                                            <ul>
                                                                <li class="colCompanyName">Company Name</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>
                                <telerik:RadComboBox ID="ddlShipTo" runat="server" AppendDataBoundItems="false"
                                datatextfield="ShipTo" DataValueField="ShipToID"
                                MarkFirstMatch="true" DropDownWidth="200px" HighlightTemplatedItems="true" Width="200px"
                                 ClientEvents-OnKeyPress="KeyPressed" ></telerik:RadComboBox>
 
 
                            </td>
                <td><telerik:RadDatePicker ID="txtPurchaseDate" runat="server"  ClientEvents-OnKeyPress="KeyPressed" Width="140px"   AutoPostBack="false"
                        DateInput-EmptyMessage="" MinDate="01/01/1000" MaxDate="01/01/3000" SelectedDate='<%# Bind("PurchaseDate") %> '>
                        <Calendar ID="Calendar1" runat="server"  ClientEvents-OnKeyPress="KeyPressed">
                            <SpecialDays>
                                <telerik:RadCalendarDay Repeatable="Today" ItemStyle-CssClass="rcToday" />
                            </SpecialDays>
                        </Calendar>
                    </telerik:RadDatePicker></td>
                          </tr>
                          <tr>
                            <td colspan="3" align="center">
                                <table width="100%" border="0" cellpadding="1" cellspacing="0">
                                    <tr>
                                        <td width="175px" 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="75px" align="left"><asp:Label ID="Label21" runat="server" Text="Extension" Font-Bold="true"></asp:Label></td>
                                    </tr>
                                </table>
                                 
                            </td>
                          </tr>
                          <tr>
                            <td colspan="3" align="center">
                                <table width="100%" border="0" cellpadding="1" cellspacing="0">
                                    <tr>
                                        <td width="175px" 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="175px" 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" AppendDataBoundItems="false" AutoPostBack="false"
                                                        EmptyMessage="Select..." DataSourceID="dsProducts" DataTextField="Product"  DataValueField="CPProductID" SelectedValue='<%# Bind("CPProductID") %>' MarkFirstMatch="true" DropDownWidth="500px" HighlightTemplatedItems="true" Width="175px" Height="250px"   ClientEvents-OnKeyPress="KeyPressed"  OnItemDataBound="ddlProduct_ItemDataBound"  EnableLoadOnDemand="false" >
                                                        <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"><%# Eval("Product")%></li>
                                                                <li class="colSize" ><%# Eval("Size")%></li>
                                                                <li class="colSuppleer"><%# Eval("SupplierName")%></li>  
                                                            </ul>
                                                        </ItemTemplate>
                                                        </telerik:RadComboBox></td>
                                        <td width="75px" align="left"><telerik:RadTextBox ID="txtSize" runat="server" ReadOnly="true" Width="75px"></telerik:RadTextBox></td>
                                        <td width="150px" align="left"><telerik:RadTextBox ID="txtManufacturer" runat="server" ReadOnly="true" Width="150px"></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="100%" NumberFormat-GroupSeparator="" invalidstyleduration="100" Dbvalue='<%# Bind("Quantity") %>' > </telerik:RadNumericTextBox></td>
                                        <td width="75px" align="left"><telerik:RadNumericTextBox incrementsettings-interceptarrowskeys="false" incrementsettings-interceptmousewheel="false"  ID="txtPrice" runat="server" Type="currency" width="100%" EmptyMessageStyle-Width="70px"  Dbvalue='<%# Bind("Price") %>'></telerik:RadNumericTextBox></td>
                                        <td width="75px" align="left"><telerik:RadNumericTextBox incrementsettings-interceptarrowskeys="false" incrementsettings-interceptmousewheel="false"  ID="txtExtension" runat="server" Type="currency" width="100%" EmptyMessageStyle-Width="70px"  Dbvalue='<%# Bind("Extension") %>'  NumberFormat-NegativePattern="$- n"></telerik:RadNumericTextBox></td>
                                    </tr>
                                </table>
                                 
                            </td>
                          </tr>
                           
                        </table><br /></div>
                    </FormTemplate>
</EditFormSettings>
</MasterTableView>
        <ClientSettings AllowKeyboardNavigation="false">
         
         <ClientEvents OnKeyPress="CatchKeyPress" OnCommand="gridCommand" ></ClientEvents>
          
                         <Selecting AllowRowSelect="true" />
                                              <Scrolling AllowScroll="true"  UseStaticHeaders="true" />
        </ClientSettings>
        <GroupingSettings CaseSensitive="false" />
        <EditItemStyle />
                      <AlternatingItemStyle BackColor="Aqua" />
                       
 
<FilterMenu EnableImageSprites="False"></FilterMenu>
        </telerik:RadGrid>
 
            <asp:SqlDataSource ID="SqlDataSource1" runat="server"
            ConnectionString="<%$ ConnectionStrings:csPrairielandAg %>"
            ProviderName="<%$ ConnectionStrings:csPrairielandAg.ProviderName %>"
            SelectCommand="select TransactionID, a.MemberID,a.ShipToID,  PurchaseDate, a.CPDistributorID, InvoiceNumber,a.CPProductID, Product, Quantity, Price, Extension, NetPricing, DPS,e.CPSupplierID from tblCropProtectionTransactions a join tblMembers b on a.MemberID = b.MemberID join tblMembershipto c on a.ShipToID = c.ShipToId join tblCropProtectionDistributors d on a.CPDistributorID = d.CPDistributorID join tblCropProtectionProducts e on a.CPProductID = e.CPProductID join tblCropProtectionSuppliers f on e.CPSupplierID = f.CPSupplierID where DateDiff(month,PurchaseDate,getdate()) < 24 ORDER BY PurchaseDate, CompanyName"
            UpdateCommand="UPDATE dbo.tblCropProtectionDistributors SET DistributorName = @DistributorName WHERE (CPDistributorID = @CPDistributorID)"
            InsertCommand="INSERT INTO dbo.tblCropProtectionDistributors(DistributorName) VALUES ( @DistributorName)">
                <InsertParameters>
                    <asp:Parameter Name="DistributorName" />
                </InsertParameters>
            <UpdateParameters>
                <asp:Parameter Name="CPDistributorID" />
                <asp:Parameter Name="DistributorName" />
            </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 code:
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_Transactions
 
    Inherits System.Web.UI.Page
 
    Dim strMode As String = ""
    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
        ' RadGrid1.Enabled = True
        RadGrid1.Visible = True
        Session("Refresh") = "Yes"
    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"
            ' RadGrid1.EditIndexes.Clear()
            RadGrid1.MasterTableView.IsItemInserted = False
            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 image As ImageButton = DirectCast(e.CommandSource, ImageButton)
            Dim strProductID = e.Item.OwnerTableView.DataKeyValues(e.Item.ItemIndex)("CPProductID").ToString
            'strProductID = Replace(strProductID, "Delete ", "")
            Try
                Dim deleteQuery As String = "Delete from tblCropProtectionProducts where CPProductID='" & strProductID & "'"
                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("Product 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 Product as it is currently tied to a transaction.")
                Else
                    SetMessage(ex.Message)
                End If
 
 
            End Try
        End If
        If e.CommandName = "InsertProduct" Then
            RadGrid1.MasterTableView.IsItemInserted = True
            RadGrid1.Rebind()
        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
        If Session("Refresh") = "No" Then
            Exit Sub
        End If
        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
            If item.IsDataBound Then
                item.Display = False
            End If
        Next
        Label1.Visible = "False"
    End Sub
 
    Protected Sub RadGrid1_UpdateCommand(sender As Object, e As Telerik.Web.UI.GridCommandEventArgs) Handles RadGrid1.UpdateCommand
        If RadGrid1.MasterTableView.IsItemInserted = True Then
            Dim dataInsert As GridDataItem = e.Item.OwnerTableView.GetInsertItem
            Dim txtSupplier As RadComboBox = DirectCast(dataInsert("CPSupplierID").Controls(0), RadComboBox)
            Dim txtProduct As TextBox = DirectCast(dataInsert("Product").Controls(0), TextBox)
            Dim txtSize As TextBox = DirectCast(dataInsert("Size").Controls(0), TextBox)
            SqlDataSource1.InsertParameters("CPSupplierID").DefaultValue = txtSupplier.SelectedValue
            SqlDataSource1.InsertParameters("Size").DefaultValue = txtSize.Text
            SqlDataSource1.InsertParameters("Product").DefaultValue = txtProduct.Text
 
            Try
                SqlDataSource1.Insert()
                RadGrid1.MasterTableView.IsItemInserted = False
                Label1.Visible = False
                '  RadGrid1.EditIndexes.Clear()
            Catch ex As Exception
                SetMessage(Server.HtmlEncode("Unable to update Product. Reason: " + ex.StackTrace).Replace("'", "'").Replace(vbCrLf, "<br />"))
            End Try
        End If
 
        If RadGrid1.Items.Item(1).IsInEditMode = True Then
            For Each dataItem As GridDataItem In RadGrid1.MasterTableView.Items
                Dim newValues As New Hashtable()
                Dim eeditedItem As GridEditableItem = TryCast(e.Item, GridEditableItem)
                Dim intProductID As Integer = dataItem.OwnerTableView.DataKeyValues(dataItem.ItemIndex)("CPProductID")
                RadGrid1.MasterTableView.ExtractValuesFromItem(newValues, dataItem)
                SqlDataSource1.UpdateParameters("CPProductID").DefaultValue = intProductID
                SqlDataSource1.UpdateParameters("CPSupplierID").DefaultValue = newValues("CPSupplierID")
                SqlDataSource1.UpdateParameters("Product").DefaultValue = newValues("Product")
                SqlDataSource1.UpdateParameters("Size").DefaultValue = newValues("Size")
                Try
                    SqlDataSource1.Update()
                    RadGrid1.MasterTableView.IsItemInserted = False
                    Label1.Visible = False
                    '  RadGrid1.EditIndexes.Clear()
                Catch ex As Exception
                    SetMessage(Server.HtmlEncode("Unable to update Product. Reason: " + ex.StackTrace).Replace("'", "'").Replace(vbCrLf, "<br />"))
                End Try
            Next
 
        Else
            Exit Sub
        End If
 
    End Sub
    Private Sub SetMessage(ByVal message As String)
        Label1.Text = String.Format("<span style='color:red'>{0}</span>", message)
        Label1.Visible = True
    End Sub
 
    Protected Sub ddlProduct_ItemDataBound(sender As Object, e As RadComboBoxItemEventArgs)
        Dim row As DataRowView = TryCast(e.Item.DataItem, DataRowView)
        e.Item.Attributes("Product") = row("Product").ToString()
        e.Item.Attributes("Size") = row("Size").ToString()
        e.Item.Attributes("SupplierName") = row("SupplierName").ToString()
        'e.Item.Attributes.Add("onchange", "return ddlProductChanged('" + e.Item.ClientID + "',Null,Null, event);")
    End Sub
 
    Protected Sub ddlProduct_SelectedIndexChanged(o As Object, e As Telerik.Web.UI.RadComboBoxSelectedIndexChangedEventArgs)
        Dim editedItem As GridEditableItem = TryCast(TryCast(o, RadComboBox).NamingContainer, GridEditableItem)
        Dim productCombo As RadComboBox = TryCast(o, RadComboBox)
        'Dim  As RadComboBox = TryCast(editedItem.FindControl("ddlShipTo"), RadComboBox)
        'ddlShipTo.Text = ""
        'ddlShipTo.DataSource = LoadShipTo(e.Value)
        'ddlShipTo.DataBind()
        Dim txtSize As RadTextBox = TryCast(editedItem.FindControl("txtSize"), RadTextBox)
        Dim txtManufacturer As RadTextBox = TryCast(editedItem.FindControl("txtManufacturer"), RadTextBox)
        txtSize.Text = productCombo.SelectedItem.Attributes("Size").ToString
        txtManufacturer.Text = productCombo.SelectedItem.Attributes("SupplierName").ToString
        Session("Refresh") = "No"
    End Sub
    Protected Sub ddlMember_SelectedIndexChanged(o As Object, e As Telerik.Web.UI.RadComboBoxSelectedIndexChangedEventArgs)
        Dim editedItem As GridEditableItem = TryCast(TryCast(o, RadComboBox).NamingContainer, GridEditableItem)
        Dim membersCombo As RadComboBox = TryCast(o, RadComboBox)
        Dim ddlShipTo As RadComboBox = TryCast(editedItem.FindControl("ddlShipTo"), RadComboBox)
        ddlShipTo.Text = ""
        ddlShipTo.DataSource = LoadShipTo(e.Value)
        ddlShipTo.DataBind()
        Session("Refresh") = "No"
 
    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)
 
            If e.Item.OwnerTableView.IsItemInserted Then
                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()
            Else
                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)
                txtSize.Text = productCombo.SelectedItem.Attributes("Size").ToString
                txtManufacturer.Text = productCombo.SelectedItem.Attributes("SupplierName").ToString
            End If
        End If
 
    End Sub
 
 
End Class


2 Answers, 1 is accepted

Sort by
0
ADT
Top achievements
Rank 1
answered on 29 Nov 2012, 04:39 PM
Thanks for the links Jayesh. Your examples looped through the edit controls so I needed to make some modifications, but it was still helpful. What I ended up having to do was  set the javascript to call on item created passing in the item index:
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);}"
 
    End If
End Sub

Then in the javascript I used the following
function Selected(rowIndex, eventArgs) {
    var grid = $find("<%= RadGrid1.ClientID %>");
    if (grid) {
        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");
 
    }
}

This makes the grid run much smoother then having to do a post-back as it takes a bit to load due to the # of records in a few of the dropdowns.

Thanks
Tags
Grid
Asked by
ADT
Top achievements
Rank 1
Answers by
Jayesh Goyani
Top achievements
Rank 2
ADT
Top achievements
Rank 1
Share this question
or