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

GridEditFormItem vs. GridDataItem

4 Answers 431 Views
Grid
This is a migrated thread and some comments may be shown as answers.
areen
Top achievements
Rank 1
areen asked on 25 Feb 2011, 07:17 PM
hi. I've got a asp:button on my formtemplate. when i call it from the insert form, i get passed a grideditform item. but when i call it from the update form, i get passed a griddataitem. i need to access the controls on this form and can't seem to get to them from the griddataitem. please help.

thanks!

.aspx
    <asp:Label ID="Label1" runat="server" Text=""></asp:Label>
    <telerik:RadGrid ID="RadGrid4" runat="server"
    AllowPaging="True" PageSize="20" AllowSorting="True" AutoGenerateColumns="False" DataSourceID="SqlDataSource4" OnNeedDataSource="RadGrid4_NeedDataSource"
    OnItemCreated="RadGrid4_ItemCreated" OnInsertCommand="RadGrid4_InsertCommand" OnUpdateCommand="RadGrid4_UpdateCommand" OnDeleteCommand="RadGrid4_DeleteCommand"
    OnItemCommand="RadGrid4_ItemCommand"
    GridLines="None">
<MasterTableView datakeynames="GeoLocationId" datasourceid="SqlDataSource4" CommandItemDisplay="TopAndBottom">
<CommandItemSettings ExportToPdfText="Export to Pdf"></CommandItemSettings>
 
<RowIndicatorColumn FilterControlAltText="Filter RowIndicator column">
<HeaderStyle Width="20px"></HeaderStyle>
</RowIndicatorColumn>
 
<ExpandCollapseColumn FilterControlAltText="Filter ExpandColumn column">
<HeaderStyle Width="20px"></HeaderStyle>
</ExpandCollapseColumn>
 
    <Columns>
        <telerik:GridEditCommandColumn FilterControlAltText="Filter EditCommandColumn column">
        </telerik:GridEditCommandColumn>
        <telerik:GridButtonColumn FilterControlAltText="Filter column column"
            Text="Delete" UniqueName="column" CommandName="Delete"
            ConfirmDialogType="Classic" ConfirmTitle="Confirm Data Center Delete" ConfirmText="Are you sure you want to delete this Data Center?">
        </telerik:GridButtonColumn>
        <telerik:GridBoundColumn DataField="GeoLocationId" DataType="System.Int32"
            FilterControlAltText="Filter GeoLocationId column" HeaderText="Data Center ID"
            ReadOnly="True" SortExpression="GeoLocationId" UniqueName="GeoLocationId">
        </telerik:GridBoundColumn>
        <telerik:GridBoundColumn DataField="Name"
            FilterControlAltText="Filter Name column" HeaderText="Location"
            SortExpression="Name" UniqueName="Name">
        </telerik:GridBoundColumn>
        <telerik:GridBoundColumn DataField="Description"
            FilterControlAltText="Filter Description column" HeaderText="Name"
            SortExpression="Description" UniqueName="Description">
        </telerik:GridBoundColumn>
        <telerik:GridBoundColumn DataField="Latitude"
            FilterControlAltText="Filter Latitude column" HeaderText="Latitude"
            SortExpression="Latitude" UniqueName="Latitude">
        </telerik:GridBoundColumn>
        <telerik:GridBoundColumn DataField="Longitude"
            FilterControlAltText="Filter Longitude column" HeaderText="Longitude"
            SortExpression="Longitude" UniqueName="Longitude">
        </telerik:GridBoundColumn>
        <telerik:GridBoundColumn DataField="LoadBalancer"
            FilterControlAltText="Filter LoadBalancer column" HeaderText="LoadBalancer"
            SortExpression="LoadBalancer" UniqueName="LoadBalancer">
        </telerik:GridBoundColumn>
    </Columns>
 
<EditFormSettings EditFormType="Template">
<EditColumn UniqueName="EditCommandColumn1" FilterControlAltText="Filter EditCommandColumn1 column"></EditColumn>
    <FormTemplate>
        <table border="0" cellpadding="1" cellspacing="2" width="100%" rules="none" style="border-collapse: collapse; background: white;" id="table1">
            <tr>
                <td><asp:Label runat="server" ID="lblGeoLocationId" Text="Data Center ID:"></asp:Label></td>
                <td><asp:TextBox runat="server" ID="txtGeoLocationId" Enabled="false" Text='<%# Bind("GeoLocationId") %>'></asp:TextBox></td>
            </tr>
            <tr>
                <td>Name:</td>
                <td>
                    <asp:TextBox runat="server" ID="txtDescription" Text='<%# Bind("Description") %>'></asp:TextBox>
                    <asp:RequiredFieldValidator runat="server" ControlToValidate="txtDescription" Text="The Name field is required!"></asp:RequiredFieldValidator>
                </td>
            </tr>
            <tr>
                <td>Load Balancer:</td>
                <td>
                    <asp:TextBox runat="server" ID="txtLoadBalancer" Text='<%# Bind("LoadBalancer") %>'></asp:TextBox>
                    <asp:Button runat="server" ID="btnLoadBalancer" Text="Get Geographic Data" CommandName="GeoLookup" />
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtLoadBalancer" Text="The Load Balancer field is required!"></asp:RequiredFieldValidator>
                    <asp:RegularExpressionValidator ID="revLoadBalancer" runat="server" ControlToValidate="txtLoadBalancer" ErrorMessage="Please enter a valid IP Address." ValidationExpression="\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b"></asp:RegularExpressionValidator>
                </td>
            </tr>
            <tr>
                <td>Location:</td>
                <td>
                    <asp:TextBox runat="server" ID="txtName" Enabled="false" Text='<%# Bind("Name") %>'></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>Latitude:</td>
                <td>
                    <asp:TextBox runat="server" ID="txtLatitude" Enabled="false" Text='<%# Bind("Latitude") %>'></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>Longitude:</td>
                <td>
                    <asp:TextBox runat="server" ID="txtLongitude" Enabled="false" Text='<%# Bind("Longitude") %>'></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td align="right" colspan="2">
                    <asp:Button ID="btnUpdate" runat="server" Text='<%#  (Container is GridEditFormInsertItem) ? "Insert" : "Update" %>' CommandName='<%# (Container is GridEditFormInsertItem) ? "PerformInsert" : "Update" %>' />
                      
                    <asp:Button ID="btnCancel" runat="server" Text="Cancel" CausesValidation="false" CommandName="Cancel" />
                </td>
            </tr>
        </table>
    </FormTemplate>
</EditFormSettings>
</MasterTableView>
 
<FilterMenu EnableImageSprites="False"></FilterMenu>
 
<HeaderContextMenu CssClass="GridContextMenu GridContextMenu_Default"></HeaderContextMenu>
    </telerik:RadGrid>
    <asp:SqlDataSource ID="SqlDataSource4" runat="server"
    ConnectionString="<%$ ConnectionStrings:MgmtServerConnectionString %>"
    SelectCommand="SELECT [GeoLocationId], [Name], [Description], [Latitude], [Longitude], [LoadBalancer] FROM [GeoLocation] ORDER BY [GeoLocationId]"></asp:SqlDataSource>
.aspx.cs
protected void RadGrid4_ItemCommand(object source, GridCommandEventArgs e)
{
    string strCommandName = e.CommandName;
    if (e.CommandName == "GeoLookup")
    {
        if (e.Item is GridEditFormItem || e.Item is GridDataItem)
        {
            // instantiate form objects
            TextBox loadBalancer = null;
            TextBox location = null;
            TextBox latitude = null;
            TextBox longitude = null;
            RegularExpressionValidator revLoadBalancer = null;
 
            if (e.Item is GridEditFormItem)
            {
                GridEditFormItem item = e.Item as GridEditFormItem;
 
                // retrieve the controls from the edit form
                location = (TextBox)item.FindControl("txtName");
                latitude = (TextBox)item.FindControl("txtLatitude");
                longitude = (TextBox)item.FindControl("txtLongitude");
                loadBalancer = (TextBox)item.FindControl("txtLoadBalancer");
                revLoadBalancer = (RegularExpressionValidator)item.FindControl("revLoadBalancer");
            }
 
            if (e.Item is GridDataItem)
            {
                GridDataItem item = (GridDataItem)e.Item;
 
                // retrieve the controls from the edit form
                location = (TextBox)item.FindControl("txtName");
                latitude = (TextBox)item.FindControl("txtLatitude");
                longitude = (TextBox)item.FindControl("txtLongitude");
                loadBalancer = (TextBox)item.FindControl("txtLoadBalancer");
                revLoadBalancer = (RegularExpressionValidator)item.FindControl("revLoadBalancer");
            }
             
            string txtLoadBalancer = loadBalancer.Text;
            bool blnLoadBalancer = this.txtLoadBalancer_IsValidIP(txtLoadBalancer);
            if (blnLoadBalancer)
            {
                try
                {
                    string results = MgmtServer.App_Code.CalculateDistanceToCoast.GeoLookup(txtLoadBalancer);
                    if (results != "" && (results.IndexOf("IP_NOT_FOUND") == -1))
                    {
                        string[] Args = results.Split(new Char[] { ',' });
                        string strLocation = Convert.ToString(Args[0]) + "," + Convert.ToString(Args[1]) + "," + Convert.ToString(Args[2]);
                        string strLatitude = Convert.ToString(Args[4]);
                        string strLongitude = Convert.ToString(Args[5]);
 
                        // update the control values
                        location.Text = strLocation;
                        latitude.Text = strLatitude;
                        longitude.Text = strLongitude;
                    }
                    else
                    {
                        MgmtServer.App_Code.MgmtServerLib.SaveErrorTrackingOnTable(MgmtServer.App_Code.MgmtServerLib.Broad_CallingGeolookupReturn_Error);
                        Label1.Text = "Geographic Data Lookup returned nothing";
                    }
                }
                catch (Exception ex)
                {
                    MgmtServer.App_Code.MgmtServerLib.SaveErrorTrackingOnTable(MgmtServer.App_Code.MgmtServerLib.Broad_CallingGeolookup_Error, ex.Message, txtLoadBalancer);
                    Label1.Text = "An exception occurred calling geolookup: " + ex.Message + ":" + txtLoadBalancer;
                }
            }
            else
            {
                revLoadBalancer.ErrorMessage = "Please enter a valid IP Address.";
                revLoadBalancer.IsValid = false;
                revLoadBalancer.Validate();
            }
        }
    }
}

4 Answers, 1 is accepted

Sort by
0
Princy
Top achievements
Rank 2
answered on 28 Feb 2011, 08:37 AM
Hello Areen,

One option is setting different CommanName for button in Insert and edit mode.

ASPX:
<asp:Button runat="server" ID="btnLoadBalancer" Text="Get Geographic Data"
CommandName='<%# (Container is GridEditFormInsertItem) ? "GeoLookupInsert" : "GeoLookupUpdate" %>' />

C#:
protected void RadGrid4_ItemCommand(object sender, GridCommandEventArgs e)
   {
       if (e.CommandName == "GeoLookupInsert")
       {
          // button in insert form
       }
       if (e.CommandName == "GeoLookupUpdate")
       {
           // button in edit form
       }
   }

Thanks,
Princy.
0
areen
Top achievements
Rank 1
answered on 28 Feb 2011, 08:07 PM
Princy,

While you're feedback is much appreciated, it doesn't answer my question. I did as you suggested and the "Update" path is still returning a GridDataItem to me. how do I get to my form control values from the GridDataItem?

if (e.Item is GridDataItem)
{
    GridDataItem item = (GridDataItem)e.Item;
 
    // retrieve the controls from the edit form
    location = (TextBox)item.FindControl("txtName");
    latitude = (TextBox)item.FindControl("txtLatitude");
    longitude = (TextBox)item.FindControl("txtLongitude");
    loadBalancer = (TextBox)item.FindControl("txtLoadBalancer");
    revLoadBalancer = (RegularExpressionValidator)item.FindControl("revLoadBalancer");
}

When I retrieve control values from the edit form using findcontrol, all the objects are null. What is the correct way to access the form controls when using a GridDataItem?

Thanks,
Areen
0
Princy
Top achievements
Rank 2
answered on 01 Mar 2011, 05:55 AM
Hello Areen,

Try the following approach to get the control inside FormTemplate.

C#:
protected void RadGrid4_ItemCommand(object sender, GridCommandEventArgs e)
    {
       if (e.CommandName == "GeoLookupUpdate")
        {
            Button btn = (Button)e.CommandSource;
            GridEditFormItem editItem = (GridEditFormItem)btn.NamingContainer;
            TextBox txt = (TextBox)editItem.FindControl("txtName");
        }
    }

Hope this helps,
Princy.
0
areen
Top achievements
Rank 1
answered on 01 Mar 2011, 07:43 PM
Princy,

Thanks so much. This did the trick. I had tried to access via the source object but not the command source. Whew.

Areen
Tags
Grid
Asked by
areen
Top achievements
Rank 1
Answers by
Princy
Top achievements
Rank 2
areen
Top achievements
Rank 1
Share this question
or