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

Adding editform button from code behind

7 Answers 331 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Cyrus
Top achievements
Rank 1
Cyrus asked on 15 Oct 2009, 03:17 PM

I have been struggling with a problem for the last few days and finally found a solution.  It wasn’t a sophisticated fix so I wanted to know if there is a better way to do this.  I have a custom CommandName that looks up data in an asset database so that the user can enter an asset tag to populate the rest of the editform dynamically.  I have also added an extra button that is created when the PerfromInsertButton is present.    Previously I had this attached to the CancelButton but when I tried using my custom  CommandName from Edit (as opposed to Insert) I got an error saying “Index was out of Range”. 

 

Long story short, I decided to just attach my custom button to the PerfromInsertButton button so that it only shows up on Insert and not Edit.  It isn’t elegant but I was hoping for a better outcome.

 

Any ideas?

My RadGrid

 

<telerik:RadGrid ID="transferGrid" runat="server" DataSourceID="transferData" GridLines="None" 
                AllowAutomaticInserts="True" Skin="Office2007" AutoGenerateColumns="False" AllowAutomaticDeletes="True" 
                Visible="false" AutoGenerateEditColumn="true" AllowAutomaticUpdates="true">  
                <HeaderContextMenu EnableTheming="True">  
                    <CollapseAnimation Type="OutQuint" Duration="200"></CollapseAnimation> 
                </HeaderContextMenu> 
                <ClientSettings> 
                    <Selecting AllowRowSelect="True" /> 
                </ClientSettings> 
                <MasterTableView DataKeyNames="ID" DataSourceID="transferData" EditMode="EditForms" 
                    CommandItemDisplay="Bottom">  
                    <NoRecordsTemplate> 
                        <asp:Label runat="server" Text="No Assets have been added"></asp:Label> 
                    </NoRecordsTemplate>                     
                    <CommandItemTemplate> 
                        <div class="noprint" style="text-align: right;">  
                            <asp:Button ID="btnAdd" runat="server" Text="Add New Asset" CommandName="InitInsert">  
                            </asp:Button> 
                            <asp:Button ID="btnDelete" runat="server" Text="Delete Selected Asset" ToolTip="Click asset to select" 
                                CommandName="DeleteSelected"></asp:Button> 
                        </div> 
                    </CommandItemTemplate> 
                  <EditFormSettings> 
                        <EditColumn UniqueName="InsertCommandColumn" ButtonType="PushButton" ItemStyle-Font-Bold="true" 
                            InsertText="Save Asset">                              
                        </EditColumn>                                                                                       
                    </EditFormSettings> 
                    <RowIndicatorColumn> 
                        <HeaderStyle Width="20px"></HeaderStyle> 
                    </RowIndicatorColumn> 
                    <ExpandCollapseColumn> 
                        <HeaderStyle Width="20px"></HeaderStyle> 
                    </ExpandCollapseColumn> 
                    <Columns> 
                        <telerik:GridBoundColumn DataField="ID" HeaderText="ID" SortExpression="ID" UniqueName="ID" 
                            DataType="System.Int32" ReadOnly="True" Visible="false">  
                        </telerik:GridBoundColumn> 
                        <telerik:GridBoundColumn DataField="Manufacturer_Name" HeaderText="Manufacturer Name" 
                            SortExpression="Manufacturer_Name" UniqueName="Manufacturer_Name" MaxLength="30">  
                        </telerik:GridBoundColumn> 
                        <telerik:GridBoundColumn DataField="Model" HeaderText="Model" SortExpression="Model" 
                            UniqueName="Model" MaxLength="18">  
                        </telerik:GridBoundColumn> 
                        <telerik:GridBoundColumn DataField="Tag" HeaderText="Tag" SortExpression="Tag" UniqueName="Tag" 
                            MaxLength="8">  
                        </telerik:GridBoundColumn>                          
                        <telerik:GridBoundColumn DataField="PO" HeaderText="PO" SortExpression="PO" UniqueName="PO" 
                            MaxLength="10">  
                        </telerik:GridBoundColumn> 
                        <telerik:GridBoundColumn DataField="Serial" HeaderText="Serial" SortExpression="Serial" 
                            UniqueName="Serial" MaxLength="18">  
                        </telerik:GridBoundColumn> 
                        <telerik:GridBoundColumn DataField="Value" HeaderText="Value" SortExpression="Value" 
                            UniqueName="Value" MaxLength="8">  
                        </telerik:GridBoundColumn> 
                        <telerik:GridEditCommandColumn Display="false"></telerik:GridEditCommandColumn>    
                    </Columns> 
                </MasterTableView> 
                <FilterMenu EnableTheming="True">  
                    <CollapseAnimation Type="OutQuint" Duration="200"></CollapseAnimation> 
                </FilterMenu> 
            </telerik:RadGrid> 

Code Behind
Protected Sub transferGrid_ItemCreated(ByVal sender As Object, ByVal e As Telerik.Web.UI.GridItemEventArgs) Handles transferGrid.ItemCreated  
        If TypeOf e.Item Is Telerik.Web.UI.GridEditFormItem AndAlso e.Item.IsInEditMode Then  
            Dim linkButton As New Button  
            linkButton.Text = "Lookup Tag" 
            linkButton.CommandName = "LookupTag" 
            linkButton.CausesValidation = False 
            linkButton.Attributes("onclick") = "javascript:return confirm('Lookup will use the Asset Tag to fill out details. If asset is not found, data will not be returned.')"  
            Try  
                Dim cancel As Button = TryCast(e.Item.FindControl("PerformInsertButton"), Button)  
                cancel.Parent.Controls.Add(New LiteralControl(" "))  
                cancel.Parent.Controls.Add(linkButton)  
            Catch ex As Exception  
 
            End Try  
 
        End If  
 
    End Sub  
 
 Protected Sub transferGrid_ItemCommand(ByVal source As Object, ByVal e As Telerik.Web.UI.GridCommandEventArgs) Handles transferGrid.ItemCommand  
        If e.CommandName = "InitInsert" Or e.CommandName = "Edit" Then  
            'btnPrintEmail.Enabled = False 
            transferGrid.MasterTableView.CommandItemDisplay = GridCommandItemDisplay.None  
            'lookuptagButton.Visible = False 
            'Dim lookupTag As Button = TryCast(e.Item.FindControl("LookupTag"), Button) 'INDEX ERROR HERE ON EDIT SAVE....INSERT WORKED FINE 
            'lookupTag.Visible = False 
 
        ElseIf e.CommandName = "LookupTag" Then  
            Dim item As GridEditableItem = CType(e.Item, GridEditableItem)  
            'Dim tagText As String = CType(item("Tag").Controls(0), TextBox).Text  
            'Dim editedItem As GridEditableItem = CType(e.Item, GridEditableItem)  
            'Dim itemValue As String = item("Tag").Text  
            Dim cell As TableCell = item("Tag")  
            Dim itemValue As String = (CType(cell.Controls(0), TextBox)).Text 'INDEX ERROR HERE ONLY WHEN TRYING TO SAVE AFTER EDIT  
 
            'MessageBox(itemValue)  
            Dim accessConnection As SqlConnection = New SqlConnection()  
            Dim cn As OleDb.OleDbConnection = New OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + System.Web.HttpContext.Current.Server.MapPath("~/App_Data/ReceivingLog.mdb"))  
            'provider to be used when working with access database  
            cn.Open()  
            'calculate mins, hrs played  
            Dim cmd As OleDb.OleDbCommand = New OleDb.OleDbCommand("SELECT [Make], [Model], [SerialNum], [PO] FROM [tblReceivingLog] WHERE [InventoryNum] = '" & itemValue & "'", cn)  
            Dim dr = cmd.ExecuteReader  
            While dr.Read  
                CType(item("Manufacturer_Name").Controls(0), TextBox).Text = dr(0)  
                CType(item("Model").Controls(0), TextBox).Text = dr(1)  
                CType(item("Serial").Controls(0), TextBox).Text = dr(2)  
                CType(item("PO").Controls(0), TextBox).Text = dr(3)  
            End While  
 
            cn.Close()  
        Else  
            'btnPrintEmail.Enabled = True 
            'transferGrid.MasterTableView.GetColumn("LookupTag").Display = False 
            transferGrid.MasterTableView.CommandItemDisplay = GridCommandItemDisplay.Bottom  
        End If  
 
    End Sub 

 

7 Answers, 1 is accepted

Sort by
0
Thomas Salt
Top achievements
Rank 1
answered on 15 Oct 2009, 05:50 PM
My suggestion would be to create a grid template column with your custom button in it and then hide/show this column based on your criteria.
0
Cyrus
Top achievements
Rank 1
answered on 15 Oct 2009, 05:55 PM
Could you elaborate?  Perhaps some sample code?  This is very confusing.
0
Thomas Salt
Top achievements
Rank 1
answered on 15 Oct 2009, 06:22 PM
check out this page
http://demos.telerik.com/aspnet-ajax/grid/examples/programming/commanditem/defaultcs.aspx

specifically the <commandItemTemplate> in the radgrid declaration in the ASPX page.



0
Cyrus
Top achievements
Rank 1
answered on 15 Oct 2009, 06:24 PM
Thanks....I would still like to know what I am getting an index out of range error on updates and not inserts...thanks for the info.
0
Thomas Salt
Top achievements
Rank 1
answered on 16 Oct 2009, 02:14 PM
Can you post the stack trace please?  Or a picture of the actual error page?
Thanks.
0
Cyrus
Top achievements
Rank 1
answered on 16 Oct 2009, 04:46 PM
Server Error in '/shippingform' Application.  
--------------------------------------------------------------------------------  
 
Specified argument was out of the range of valid values.  
Parameter name: index   
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.   
 
Exception Details: System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values.  
Parameter name: index  
 
Source Error:   
 
 
Line 411:            'Dim itemValue As String = item("Tag").Text  
Line 412:            Dim cell As TableCell = item("Tag")  
Line 413:            Dim itemValue As String = (CType(cell.Controls(0), TextBox)).Text  
Line 414:  
Line 415:            'MessageBox(itemValue)  
   
 
Source File: C:\inetpub\wwwroot\shippingform\Default.aspx.vb    Line: 413   
 
Stack Trace:   
 
 
[ArgumentOutOfRangeException: Specified argument was out of the range of valid values.  
Parameter name: index]  
   System.Web.UI.ControlCollection.get_Item(Int32 index) +8670414  
   _Default.transferGrid_ItemCommand(Object source, GridCommandEventArgs e) in C:\inetpub\wwwroot\shippingform\Default.aspx.vb:413  
   Telerik.Web.UI.RadGrid.OnItemCommand(GridCommandEventArgs e) +78  
   Telerik.Web.UI.RadGrid.OnBubbleEvent(Object source, EventArgs e) +77  
   System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +37  
   Telerik.Web.UI.GridEditFormItem.OnBubbleEvent(Object source, EventArgs e) +299  
   System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +37  
   System.Web.UI.WebControls.Button.OnCommand(CommandEventArgs e) +118  
   System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +166  
   System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10  
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13  
   System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +36  
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1565  
 
   
 
0
Thomas Salt
Top achievements
Rank 1
answered on 16 Oct 2009, 06:33 PM

If e.CommandName = "InitInsert" Or e.CommandName = "Edit" Then   
            'btnPrintEmail.Enabled = False  
            transferGrid.MasterTableView.CommandItemDisplay = GridCommandItemDisplay.None   
            'lookuptagButton.Visible = False  
            'Dim lookupTag As Button = TryCast(e.Item.FindControl("LookupTag"), Button) 'INDEX ERROR HERE ON EDIT SAVE....INSERT WORKED FINE  
             
'IT MAKES SENSE THE ABOVE LINE DOES NOT WORK FOR THE EDIT FORM BECAUSE YOU ARE 
 'ADDING THE LOOKUPTAG BUTTON INTO THE INSERT FORM COMMAND TEMPLATE.   
'YOU NEED TO ADD IT TO BOTH EDIT AND INSERT FORM TEMPLATES  IN YOUR "ITEMCREATED" EVENT BY PERFORMING THE 
' FOLLOWING CHECK AND ADDING THE LOOKUP TAG TO THE CORRECT BUTTON 
Protected Sub RadGrid1_ItemCreated(ByVal sender As ObjectByVal e As Telerik.Web.UI.GridItemEventArgs) Handles RadGrid1.ItemCreated 
        If TypeOf e.Item Is GridEditableItem AndAlso e.Item.IsInEditMode Then 
 
If Not e.Item.OwnerTableView.IsItemInserted Then 
                Dim updateButton As LinkButton = CType(e.Item.FindControl("UpdateButton"), LinkButton) 
            Else 
                Dim insertButton As LinkButton = CType(e.Item.FindControl("PerformInsertButton"), LinkButton) 
 
     End If 
End If 
 ElseIf e.CommandName = "LookupTag" Then   
            Dim item As GridEditableItem = CType(e.Item, GridEditableItem)   
            'Dim tagText As String = CType(item("Tag").Controls(0), TextBox).Text   
            'Dim editedItem As GridEditableItem = CType(e.Item, GridEditableItem)   
            'Dim itemValue As String = item("Tag").Text   
            Dim cell As TableCell = item("Tag")   
            Dim itemValue As String = (CType(cell.Controls(0), TextBox)).Text 'INDEX ERROR HERE ONLY WHEN TRYING TO SAVE AFTER EDIT   
 
'THIS ERROR IS OCCURRING BECAUSE YOU ARE PERFORMING ACTIONS ON A TABLE ROW THAT  
'IS NOT CURRENTLY IN EDIT MODE.  IF YOU CHECK TO SEE IF THE ITEM TYPE IS OF 
' EDITITEM AND ONLY RUN THIS CODE WHEN IT IS OF TYPE EDITITEM THEN YOU WILL 
' SEE THAT THE ABOVE CODE WILL NOT EVER BE HIT. 
  


Tags
Grid
Asked by
Cyrus
Top achievements
Rank 1
Answers by
Thomas Salt
Top achievements
Rank 1
Cyrus
Top achievements
Rank 1
Share this question
or