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

Telerik Grid Not Returning Correct ID When Paging Enabled

8 Answers 56 Views
Grid
This is a migrated thread and some comments may be shown as answers.
James
Top achievements
Rank 1
James asked on 11 Oct 2013, 04:48 PM
Hello Support,

I am experiencing an issue with the Telerik Grid where I'm trying to delete a customer using
gvCustomers_DeleteCommand(object sender, GridCommandEventArgs e)and the incorrect Customer ID
is being passed. I believe this is happening because of paging is enabled.

What am I doing wrong?  Thanks for your help in advance.

See code below:

<
telerik:RadGrid ID="gvCustomers" runat="server"
        AllowPaging="true"
        AllowSorting="true"
        AllowAutomaticDeletes="true"
        AutoGenerateColumns="false"
        PageSize="10"
        DataKeyNames="CustomerId"
        OnItemCreated="gvCustomers_ItemCreated"
        OnItemCommand="gvCustomers_ItemCommand"
        OnItemDeleted="gvCustomers_ItemDeleted"
        OnDeleteCommand="gvCustomers_DeleteCommand"
        OnNeedDataSource="gvCustomers_NeedDataSource">
 
        <ClientSettings EnableRowHoverStyle="true" EnableAlternatingItems="true">
            <Selecting AllowRowSelect="true" />
            <ClientEvents OnRowDblClick="RowDblClick" />
        </ClientSettings>
 
        <ExportSettings HideStructureColumns="true" ExportOnlyData="true" />
 
        <MasterTableView AutoGenerateColumns="false" DataKeyNames="CustomerId"
            ClientDataKeyNames="CustomerId" CommandItemDisplay="Top">
            <CommandItemSettings
                ShowAddNewRecordButton="false"
                ShowExportToCsvButton="true"
                ShowRefreshButton="false" />
            <Columns>
 
                <telerik:GridTemplateColumn HeaderText="Edit" UniqueName="EditCustomer">
                    <ItemTemplate>
                        <asp:HyperLink ID="hlEditCustomer" runat="server" ToolTip="Update Customer Record" Text="Edit" ImageUrl="images/glyphicons_halflings_060_pencil.png" />
                    </ItemTemplate>
                </telerik:GridTemplateColumn>
 
                <telerik:GridTemplateColumn HeaderText="Transactions" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center" UniqueName="CustomerTransactions">
                    <ItemTemplate>
                        <asp:HyperLink ID="hlTransactions" runat="server" ToolTip="Customer Transactions" ImageUrl="~/images/glyphicons_halflings_031_list-alt.png" />
                    </ItemTemplate>
                </telerik:GridTemplateColumn>
 
                <telerik:GridTemplateColumn HeaderText="New Sale" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center" UniqueName="CustomerSales">
                    <ItemTemplate>
                        <asp:HyperLink ID="hlNewSale" runat="server" ToolTip="New Customer Sale" ImageUrl="~/images/glyphicons_halflings_147_usd.png" />
                    </ItemTemplate>
                </telerik:GridTemplateColumn>
 
                <telerik:GridBoundColumn DataField="CustomerId" HeaderText="Customer ID" SortExpression="CustomerId" />
                <telerik:GridBoundColumn DataField="LastName" HeaderText="Last Name" SortExpression="LastName" />
                <telerik:GridBoundColumn DataField="FirstName" HeaderText="First Name" SortExpression="FirstName" />
                <telerik:GridBoundColumn DataField="Organization" HeaderText="Organization" SortExpression="Organization" />
                <telerik:GridBoundColumn DataField="Address1" HeaderText="Address" SortExpression="Address1" />
                <telerik:GridBoundColumn DataField="Address2" HeaderText="Address 2" SortExpression="Address2" Visible="false" />
                <telerik:GridBoundColumn DataField="City" HeaderText="City" SortExpression="City" />
                <telerik:GridBoundColumn DataField="State" HeaderText="State" SortExpression="State" />
                <telerik:GridBoundColumn DataField="PostalCode" HeaderText="PostalCode" SortExpression="PostalCode" />
 
                <telerik:GridButtonColumn
                    UniqueName="DeleteCustomer"
                    ConfirmText="Are you sure you want to delete this customer?"
                    ConfirmDialogType="Classic"
                    ConfirmTitle="Delete"
                    ButtonType="ImageButton"
                    CommandName="Delete"
                    CommandArgument="CustomerId"
                    HeaderText="Delete"
                    HeaderStyle-Width="20"
                    HeaderStyle-HorizontalAlign="Center"
                    ItemStyle-HorizontalAlign="Center"
                    ImageUrl="~/images/glyphicons_halflings_019_trash.png" />
            </Columns>
        </MasterTableView>
 </telerik:RadGrid>
  
protected void gvCustomers_DeleteCommand(object sender, GridCommandEventArgs e)
{
        var item = (GridDataItem)e.Item;

           // This is return the incorrect CustomerId because of paging.
        var id = item.GetDataKeyValue("CustomerId").ToString();
 
        var customer = new Customer(id);
        customer.Delete();
 
        ClientScript.RegisterStartupScript(Page.GetType(), "mykey", "CloseAndRebind();", true);
 
        // Click the Search button
        btnSearch_Click(sender, e);
        //e.Item.OwnerTableView.ParentItem.OwnerTableView.Rebind();
 }

8 Answers, 1 is accepted

Sort by
0
Accepted
Jayesh Goyani
Top achievements
Rank 2
answered on 14 Oct 2013, 05:47 AM
Hello,

Method 1:
protected void RadGrid1_ItemCommand(object sender, GridCommandEventArgs e)
   {
       string strCustomerId = ((e.CommandSource as ImageButton).NamingContainer as GridDataItem)["CustomerId"].Text;
   }


Method 2:
protected void RadGrid1_ItemCommand(object sender, GridCommandEventArgs e)
  {
      string strCustomerId = e.CommandArgument.ToString();
  }
protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
   {
       if (e.Item is GridDataItem)
       {
           GridDataItem item = e.Item as GridDataItem;
           (item["DeleteCustomer"].Controls[0] as ImageButton).CommandArgument = item.GetDataKeyValue("CustomerId").ToString();
       }
   }


Thanks,
Jayesh Goyani
0
James
Top achievements
Rank 1
answered on 14 Oct 2013, 02:50 PM
Hi Jayesh,

I've tried both methods and I am receiving the same results. It just does not pass me the correct customer id.

See screen shot below.  Thanks.

0
James
Top achievements
Rank 1
answered on 14 Oct 2013, 03:19 PM
Jayesh,

I believe I have solved my issue. In my BindGridSearchResults method, I was using "gvCustomers.MasterTableView.DataSource = dv.Table;". I have now changed it to use "gvCustomers.DataSource = dv.Table;"  I'm not sure whats the key difference between using MasterTableView and not using it.  Thanks.

private void BindGridSearchResults()
{
        using (var dv = (DataView)Session["CustomersDataView"])
        {
            if (dv != null)
            {
                gvCustomers.MasterTableView.DataSource = dv.Table;
                gvCustomers.Rebind();
 
                var count = dv.Table.Rows.Count;
                lblSearchMessage.Visible = true;
                lblSearchMessage.Text = "Results: " + count + " customer(s) found";
            }
            else
            {
                GetSearchResults();
            }
        }
}
0
James
Top achievements
Rank 1
answered on 25 Oct 2013, 03:15 PM
This issue is still not resolved.  The problem is with the paging in the Grid.

When its turned off, it always returns the correctly ID.  And when its turned on, it random - incorrect most of the time.
0
Jayesh Goyani
Top achievements
Rank 2
answered on 28 Oct 2013, 04:32 AM
Hello,

Can you please provide your full code?
So we will try to resolve your issue.

Thanks,
Jayesh Goyani
0
James
Top achievements
Rank 1
answered on 28 Oct 2013, 02:21 PM
MARKUP

<%@ Page Title="Customers" Language="C#" MasterPageFile="~/Template.master" AutoEventWireup="true"
    CodeFile="Customers.aspx.cs" Inherits="Customers" EnableViewState="false" %>
 
<asp:Content ID="Content1" ContentPlaceHolderID="PageTitle" runat="Server">    
    <div style="float:right;">
        <div style="float: left;">
            <img src="images/glyphicons_halflings_007_user@2x.png" alt="X" />
        </div>
        <div style="float: left; padding-left: 10px;">
            <h3 style="margin:0;">Manage Customers & Place Sales</h3><asp:Label ID="lblDataSource" runat="server" />
        </div>
    </div>
</asp:Content>
 
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="Server">
    <telerik:RadCodeBlock ID="RadCodeBlock1" runat="server">       
        <script type="text/javascript">
            function ShowCustomerEditForm(id, rowIndex) {
                var grid = $find("<%= gvCustomers.ClientID %>");
 
                var rowControl = grid.get_masterTableView().get_dataItems()[rowIndex].get_element();
                grid.get_masterTableView().selectItem(rowControl, true);
 
                window.radopen("EditCustomer.aspx?ID=" + id, "customerDialog");
                return false;
            }
             
            function ShowNewSaleForm(id, rowIndex) {
                var grid = $find("<%= gvCustomers.ClientID %>");
 
                var rowControl = grid.get_masterTableView().get_dataItems()[rowIndex].get_element();
                grid.get_masterTableView().selectItem(rowControl, true);
 
                window.radopen("CustomerNewSale.aspx?ID=" + id, "newSaleDialog");
 
                //showWindowInPercentage(80);
 
                return false;
            }
 
            function ShowTransactionsForm(id, rowIndex) {
                var grid = $find("<%= gvCustomers.ClientID %>");
 
                var rowControl = grid.get_masterTableView().get_dataItems()[rowIndex].get_element();
                grid.get_masterTableView().selectItem(rowControl, true);
 
                window.radopen("CustomerTransactions.aspx?ID=" + id, "customerTransactionsDialog");
                return false;
            }
 
            function ShowInsertForm() {
                window.radopen("EditCustomer.aspx", "customerDialog");
                return false;
            }
        
            function RowDblClick(sender, eventArgs) {
                window.radopen("EditCustomer.aspx?ID=" + eventArgs.getDataKeyValue("CustomerId"), "customerDialog");
            }
 
            function onRequestStart(sender, args) {
                if (args.get_eventTarget().indexOf("ExportTo") >= 0) {
                    args.set_enableAjax(false);
                }
            }
        </script>
    </telerik:RadCodeBlock>
 
    <telerik:RadAjaxLoadingPanel ID="gridLoadingPanel" runat="server" />
 
    <telerik:RadAjaxManager ID="RadAjaxManager1" runat="server" OnAjaxRequest="RadAjaxManager1_AjaxRequest"
        ClientEvents-OnRequestStart="onRequestStart">
        <AjaxSettings>
            <telerik:AjaxSetting AjaxControlID="RadAjaxManager1">
                <UpdatedControls>
                    <telerik:AjaxUpdatedControl ControlID="gvCustomers" LoadingPanelID="gridLoadingPanel" />
                </UpdatedControls>
            </telerik:AjaxSetting>
            <telerik:AjaxSetting AjaxControlID="gvCustomers">
                <UpdatedControls>
                    <telerik:AjaxUpdatedControl ControlID="gvCustomers" LoadingPanelID="gridLoadingPanel" />
                    <telerik:AjaxUpdatedControl ControlID="RadWindowManager1" />
                </UpdatedControls>
            </telerik:AjaxSetting>
        </AjaxSettings>
    </telerik:RadAjaxManager>
 
    <div class="panel panel-default">
        <div class="panel-heading">You can place a new sale order for a customer, search for a customer and their orders, and manage their information.</div>
        <div class="panel-body">
            <div style="clear:both; float:right; text-align:right;">
                <button type="button" data-loading-text="Loading..." class="btn btn-success" onclick="return ShowInsertForm();">
                    Add a new customer
                </button>
            </div>
            <table>
                <tr>
                    <td class="right">Customer ID: </td>
                    <td>
                        <telerik:RadTextBox ID="txtSearchCustomerId" runat="server" ClientIDMode="Static" />
                    </td>
                </tr>
                <tr>
                    <td class="right">Organization: </td>
                    <td colspan="2">
                        <telerik:RadAutoCompleteBox ID="txtSearchOrganization" runat="server"
                            ClientIDMode="Static"
                            Width="400"
                            DropDownWidth="400"
                            DropDownHeight="500"
                            Filter="Contains"
                            AllowCustomEntry="true"
                            InputType="Text"
                            DataTextField="Organization"
                            DataValueField="Organization"
                            RenderMode="Lightweight"
                            TextSettings-SelectionMode="Single" />
                    </td>
                </tr>
                <tr>
                    <td class="right">Last Name: </td>
                    <td><telerik:RadTextBox ID="txtSearchLastName" runat="server" Width="200" ClientIDMode="Static" /></td>
                </tr>
                <tr>
                    <td class="right">First Name: </td>
                    <td><telerik:RadTextBox ID="txtSearchFirstName" runat="server" Width="200" ClientIDMode="Static" /></td>
                </tr>
                <tr>
                    <td></td>
                    <td style="padding-top:15px;">
                        <div style="float:left;">
                            <telerik:RadButton ID="btnSearch" runat="server" Text="Search" OnClick="btnSearch_Click" />
                            <telerik:RadButton ID="btnClear" runat="server" Text="Reset" OnClick="btnClear_Click" />
                        </div>                       
                        <div style="float:left; padding: 5px 0 0 10px;">
                            <asp:Label ID="lblSearchMessage" runat="server" EnableViewState="false" ForeColor="Red" />
                        </div>
                    </td>
                </tr>
            </table>
        </div>
    </div>
 
    <telerik:RadGrid ID="gvCustomers" runat="server"
        AllowPaging="true"
        AllowSorting="true"
        AllowAutomaticDeletes="false"
        AutoGenerateColumns="false"
        PageSize="600"
        DataKeyNames="CustomerId"
        OnItemCreated="gvCustomers_ItemCreated"
        OnItemCommand="gvCustomers_ItemCommand"
        OnDeleteCommand="gvCustomers_DeleteCommand"
        OnNeedDataSource="gvCustomers_NeedDataSource"
        OnItemDataBound="gvCustomers_ItemDataBound">
 
        <ClientSettings EnableRowHoverStyle="true" EnableAlternatingItems="true">
            <Selecting AllowRowSelect="true" />
            <ClientEvents OnRowDblClick="RowDblClick" />
        </ClientSettings>
 
        <ExportSettings HideStructureColumns="true" ExportOnlyData="true" />
 
        <MasterTableView AutoGenerateColumns="false" DataKeyNames="CustomerId"
            ClientDataKeyNames="CustomerId" CommandItemDisplay="Top">
            <CommandItemSettings
                ShowAddNewRecordButton="false"
                ShowExportToCsvButton="true"
                ShowRefreshButton="false" />
            <Columns>
 
                <telerik:GridTemplateColumn HeaderText="Edit" UniqueName="EditCustomer">
                    <ItemTemplate>
                        <asp:HyperLink ID="hlEditCustomer" runat="server" ToolTip="Update Customer Record" Text="Edit" ImageUrl="images/glyphicons_halflings_060_pencil.png" />
                    </ItemTemplate>
                </telerik:GridTemplateColumn>
 
                <telerik:GridTemplateColumn HeaderText="Transactions" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center" UniqueName="CustomerTransactions">
                    <ItemTemplate>
                        <asp:HyperLink ID="hlTransactions" runat="server" ToolTip="Customer Transactions" ImageUrl="~/images/glyphicons_halflings_031_list-alt.png" />
                    </ItemTemplate>
                </telerik:GridTemplateColumn>
 
                <telerik:GridTemplateColumn HeaderText="New Sale" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center" UniqueName="CustomerSales">
                    <ItemTemplate>
                        <asp:HyperLink ID="hlNewSale" runat="server" ToolTip="New Customer Sale" ImageUrl="~/images/glyphicons_halflings_147_usd.png" />
                    </ItemTemplate>
                </telerik:GridTemplateColumn>
 
                <telerik:GridBoundColumn DataField="CustomerId" HeaderText="Customer ID" SortExpression="CustomerId" />
                <telerik:GridBoundColumn DataField="LastName" HeaderText="Last Name" SortExpression="LastName" />
                <telerik:GridBoundColumn DataField="FirstName" HeaderText="First Name" SortExpression="FirstName" />
                <telerik:GridBoundColumn DataField="Organization" HeaderText="Organization" SortExpression="Organization" />
                <telerik:GridBoundColumn DataField="Address1" HeaderText="Address" SortExpression="Address1" />
                <telerik:GridBoundColumn DataField="Address2" HeaderText="Address 2" SortExpression="Address2" Visible="false" />
                <telerik:GridBoundColumn DataField="City" HeaderText="City" SortExpression="City" />
                <telerik:GridBoundColumn DataField="State" HeaderText="State" SortExpression="State" />
                <telerik:GridBoundColumn DataField="PostalCode" HeaderText="PostalCode" SortExpression="PostalCode" />
 
                <telerik:GridButtonColumn
                    UniqueName="DeleteCustomer"
                    ConfirmText="Are you sure you want to delete this customer?"
                    ConfirmDialogType="Classic"
                    ConfirmTitle="Delete"
                    ButtonType="ImageButton"
                    CommandName="Delete"
                    CommandArgument="CustomerId"
                    HeaderText="Delete"
                    HeaderStyle-Width="20"
                    HeaderStyle-HorizontalAlign="Center"
                    ItemStyle-HorizontalAlign="Center"
                    ImageUrl="~/images/glyphicons_halflings_019_trash.png" />
 
            </Columns>
 
        </MasterTableView>
    </telerik:RadGrid>
 
    <telerik:RadWindowManager ID="RadWindowManager1" runat="server">
        <Shortcuts>
            <telerik:WindowShortcut CommandName="CloseAll" Shortcut="Esc" />
        </Shortcuts>
        <Windows>
            <telerik:RadWindow ID="customerDialog" runat="server"
                               AutoSize="true"
                               MinWidth="750"
                               MinHeight="600"
                               KeepInScreenBounds="true"
                               Title="Edit Customer" />
 
            <telerik:RadWindow ID="customerTransactionsDialog" runat="server"
                               AutoSize="true"
                               MinWidth="1000"
                               MinHeight="200"
                               KeepInScreenBounds="true"
                               Title="Customer Transactions" />
 
            <telerik:RadWindow ID="newSaleDialog" runat="server"
                               AutoSize="true"
                               MinWidth="1000"
                               MinHeight="700"
                               KeepInScreenBounds="true"
                               Title="Customer New Sales" />
        </Windows>
    </telerik:RadWindowManager>
 
    <%--<asp:HiddenField ID="wndPercentageValue" runat="server" />--%>
 
</asp:Content>
 
<asp:Content ID="Content3" ContentPlaceHolderID="ScriptBlock" runat="Server">
    <script src="Scripts/jquery-1.9.1.min.js" type="text/javascript"></script>
    <script src="Scripts/jquery.filter_input.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $('#txtSearchCustomerId').filter_input({ regex: '[0-9]' });
            $('#txtSearchOrganization').filter_input({ regex: '[a-zA-Z 0-9]' });
            $('#txtSearchLastName').filter_input({ regex: '[a-zA-Z 0-9]' });
            $('#txtSearchFirstName').filter_input({ regex: '[a-zA-Z 0-9]' });
            $('#txtFirstName').filter_input({ regex: '[a-zA-Z 0-9]' });
            $('#txtLastName').filter_input({ regex: '[a-zA-Z 0-9]' });
        });
    </script>
</asp:Content>

BEHIND CODE

using System;
using System.Collections.Generic;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
 
public partial class Customers : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        GetUserPermissions();
        GetOrganzations();
    }
 
    private void GetUserPermissions()
    {
        if (!User.IsInRole("Administrators"))
            gvCustomers.Columns[7].Visible = false;
    }
    private void GetOrganzations()
    {
        txtSearchOrganization.DataSource = Customer.GetOrganizations();
        txtSearchOrganization.DataBind();
    }
    private void GetSearchResults()
    {
        lblSearchMessage.Visible = false;
 
        var customer = new Customer();
 
        customer.CustomerId = txtSearchCustomerId.Text;
        customer.FirstName = txtSearchFirstName.Text;
        customer.LastName = txtSearchLastName.Text;
 
        if (!string.IsNullOrWhiteSpace(txtSearchOrganization.Text))
        {
            var newString = txtSearchOrganization.Text.Length - 2;
            customer.Organization = txtSearchOrganization.Text.Substring(0, newString);
        }
        else
        {
            customer.LastName = txtSearchLastName.Text;
        }
 
        var dt = Customer.GetSearchResults(customer);
 
        if (dt != null)
        {
            Session["CustomersDataView"] = dt;
            gvCustomers.DataSource = dt;
            gvCustomers.DataBind();
 
            var count = dt.Rows.Count;
 
            if (count == 0)
            {
                lblSearchMessage.Visible = true;
                lblSearchMessage.Text = "No results found for your search criteria as of " + DateTime.Now + ".";
                gvCustomers.Visible = false;
            }
            else if (count == 1)
            {
                lblSearchMessage.Visible = true;
                lblSearchMessage.Text = "We have found <b>1</b> result for this search critera as of " + DateTime.Now + ".";
                //pnlGrid.Visible = true;
                Session["CustomersDataView"] = dt.DefaultView;
            }
            else if (count > 500)
            {
                lblSearchMessage.Visible = true;
                lblSearchMessage.Text = "Please refine your search. We have found <b>" + count + "</b> results for this search critera as of " + DateTime.Now + ".";
                gvCustomers.DataSource = null;
                gvCustomers.DataBind();
            }
            else
            {
                lblSearchMessage.Visible = true;
                lblSearchMessage.Text = "We have found <b>" + count + "</b> results for this search critera as of " + DateTime.Now + ".";
                //pnlGrid.Visible = true;
                Session["CustomersDataView"] = dt.DefaultView;
            }
        }
    }
    private int SearchCriteriaCount()
    {
        var count = 0;
 
        if (!string.IsNullOrEmpty(txtSearchCustomerId.Text)) { count++; }
        if (!string.IsNullOrEmpty(txtSearchFirstName.Text)) { count++; }
        if (!string.IsNullOrEmpty(txtSearchLastName.Text)) { count++; }
        if (!string.IsNullOrEmpty(txtSearchOrganization.Text)) { count++; }
 
        return count;
    }
    private void BindGridSearchResults()
    {
        using (var dv = (DataView)Session["CustomersDataView"])
        {
            if (dv != null)
            {
                gvCustomers.DataSource = dv.Table;
                gvCustomers.Rebind();
 
                var count = dv.Table.Rows.Count;
                lblSearchMessage.Visible = true;
                lblSearchMessage.Text = "Results: " + count + " customer(s) found";
            }
            else
            {
                GetSearchResults();
            }
        }
    }
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        if (SearchCriteriaCount() > 0)
        {
            GetSearchResults();
        }
        else
        {
            lblSearchMessage.Visible = true;
            lblSearchMessage.Text = "Please enter at least 1 search criteria.";
        }
    }
    protected void btnClear_Click(object sender, EventArgs e)
    {
        txtSearchCustomerId.Text = string.Empty;
        txtSearchFirstName.Text = string.Empty;
        txtSearchLastName.Text = string.Empty;
        txtSearchOrganization.Entries.Clear();
        gvCustomers.DataSource = null;
        gvCustomers.DataBind();
        gvCustomers.Visible = false;
        lblSearchMessage.Visible = false;
    }
 
    protected void RadAjaxManager1_AjaxRequest(object sender, AjaxRequestEventArgs e)
    {
        if (e.Argument == "Rebind")
        {
            gvCustomers.MasterTableView.SortExpressions.Clear();
            gvCustomers.MasterTableView.GroupByExpressions.Clear();
            gvCustomers.Rebind();
        }
        else if (e.Argument == "RebindAndNavigate")
        {
            gvCustomers.MasterTableView.SortExpressions.Clear();
            gvCustomers.MasterTableView.GroupByExpressions.Clear();
            gvCustomers.MasterTableView.CurrentPageIndex = gvCustomers.MasterTableView.PageCount - 1;
            gvCustomers.Rebind();
        }
 
        GetSearchResults();
    }
 
    protected void gvCustomers_ItemCreated(object sender, GridItemEventArgs e)
    {
        if (e.Item is GridDataItem)
        {
            var hlEditCustomer = (HyperLink)e.Item.FindControl("hlEditCustomer");
 
            var customerId = e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["CustomerId"];
            var customerRowIndex = e.Item.ItemIndex;
 
            hlEditCustomer.Attributes["href"] = "javascript:void(0);";
            hlEditCustomer.Attributes["onclick"] = String.Format("return ShowCustomerEditForm('{0}','{1}');", customerId, customerRowIndex);
 
            var hlNewSale = (HyperLink)e.Item.FindControl("hlNewSale");
            hlNewSale.Attributes["href"] = "javascript:void(0);";
            hlNewSale.Attributes["onclick"] = String.Format("return ShowNewSaleForm('{0}','{1}');", customerId, customerRowIndex);
 
            var hlTransactions = (HyperLink)e.Item.FindControl("hlTransactions");
            hlTransactions.Attributes["href"] = "javascript:void(0);";
            hlTransactions.Attributes["onclick"] = String.Format("return ShowTransactionsForm('{0}','{1}');", customerId, customerRowIndex);
        }
    }
 
    protected void gvCustomers_ItemCommand(object sender, GridCommandEventArgs e)
    {
        if (e.CommandName == RadGrid.ExportToCsvCommandName)
        {
            // Name of export file
            gvCustomers.ExportSettings.FileName = "Customers_Export_" + DateTime.Now.ToShortDateString();
 
            // Hide columns for exporting
            gvCustomers.MasterTableView.GetColumn("EditCustomer").Visible = false;
            gvCustomers.MasterTableView.GetColumn("CustomerTransactions").Visible = false;
            gvCustomers.MasterTableView.GetColumn("CustomerSales").Visible = false;
            gvCustomers.MasterTableView.GetColumn("DeleteCustomer").Visible = false;
 
            // Export settings
            gvCustomers.ExportSettings.ExportOnlyData = true;
            gvCustomers.ExportSettings.IgnorePaging = true;
            gvCustomers.ExportSettings.OpenInNewWindow = true;
            gvCustomers.ExportSettings.UseItemStyles = false;
        }
    }
 
    protected void gvCustomers_DeleteCommand(object sender, GridCommandEventArgs e)
    {
        var customerId = ((GridDataItem)e.Item).GetDataKeyValue("CustomerId").ToString();
 
        var operation = new Customer(customerId).Delete();
 
        ClientScript.RegisterStartupScript(Page.GetType(), "mykey", "CloseAndRebind();", true);
    }
 
    protected void gvCustomers_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
    {
        gvCustomers.DataSource = Customer.GetAllCustomers();
    }
 
    protected void gvCustomers_ItemDataBound(object sender, GridItemEventArgs e)
    {
        if (e.Item is GridDataItem)
        {
            GridDataItem item = e.Item as GridDataItem;
            (item["DeleteCustomer"].Controls[0] as ImageButton).CommandArgument = item.GetDataKeyValue("CustomerId").ToString();
        }
    }
}
0
Jayesh Goyani
Top achievements
Rank 2
answered on 29 Oct 2013, 12:33 PM
Hello,

Please try with the below code snippet.

<form id="form1" runat="server">
       <telerik:RadScriptManager ID="RadScriptManager1" runat="server"></telerik:RadScriptManager>
       <telerik:RadAjaxLoadingPanel ID="gridLoadingPanel" runat="server" />
 
       <telerik:RadAjaxManager ID="RadAjaxManager1" runat="server" OnAjaxRequest="RadAjaxManager1_AjaxRequest"
           >
           <AjaxSettings>
               <telerik:AjaxSetting AjaxControlID="RadAjaxManager1">
                   <UpdatedControls>
                       <telerik:AjaxUpdatedControl ControlID="gvCustomers" LoadingPanelID="gridLoadingPanel" />
                   </UpdatedControls>
               </telerik:AjaxSetting>
               <telerik:AjaxSetting AjaxControlID="gvCustomers">
                   <UpdatedControls>
                       <telerik:AjaxUpdatedControl ControlID="gvCustomers" LoadingPanelID="gridLoadingPanel" />
                   </UpdatedControls>
               </telerik:AjaxSetting>
           </AjaxSettings>
       </telerik:RadAjaxManager>
       <telerik:RadGrid ID="gvCustomers" runat="server"
           AllowPaging="true"
           AllowSorting="true"
           AllowAutomaticDeletes="false"
           AutoGenerateColumns="false"
           PageSize="20"
           DataKeyNames="CustomerId"
           OnDeleteCommand="gvCustomers_DeleteCommand"
           OnNeedDataSource="gvCustomers_NeedDataSource">
 
           <ClientSettings EnableRowHoverStyle="true" EnableAlternatingItems="true">
               <Selecting AllowRowSelect="true" />
 
           </ClientSettings>
 
           <ExportSettings HideStructureColumns="true" ExportOnlyData="true" />
 
           <MasterTableView AutoGenerateColumns="false" DataKeyNames="CustomerId"
               ClientDataKeyNames="CustomerId" CommandItemDisplay="Top">
               <CommandItemSettings
                   ShowAddNewRecordButton="false"
                   ShowExportToCsvButton="true"
                   ShowRefreshButton="false" />
               <Columns>
                   <telerik:GridBoundColumn DataField="CustomerId" HeaderText="Customer ID" SortExpression="CustomerId" />
                   <telerik:GridBoundColumn DataField="LastName" HeaderText="Last Name" SortExpression="LastName" />
                   <telerik:GridBoundColumn DataField="FirstName" HeaderText="First Name" SortExpression="FirstName" />
                   <telerik:GridButtonColumn
                       UniqueName="DeleteCustomer"
                       ConfirmText="Are you sure you want to delete this customer?"
                       ConfirmDialogType="Classic"
                       ConfirmTitle="Delete"
                       ButtonType="ImageButton"
                       CommandName="Delete"
                       CommandArgument="CustomerId"
                       HeaderText="Delete"
                       HeaderStyle-Width="20"
                       HeaderStyle-HorizontalAlign="Center"
                       ItemStyle-HorizontalAlign="Center"
                       ImageUrl="~/images/glyphicons_halflings_019_trash.png" />
 
               </Columns>
 
           </MasterTableView>
       </telerik:RadGrid>
   </form>
protected void gvCustomers_DeleteCommand(object sender, GridCommandEventArgs e)
  {
      var customerId = ((GridDataItem)e.Item).GetDataKeyValue("CustomerId").ToString();
  }
  protected void gvCustomers_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
  {
      DataTable dt = new DataTable();
      dt.Columns.Add("CustomerId", typeof(int));
      dt.Columns.Add("LastName", typeof(string));
      dt.Columns.Add("FirstName", typeof(string));
 
      for (int i = 0; i < 50; i++)
      {
          dt.Rows.Add(i, "lastname" + i, "firstname" + i);
      }
 
      gvCustomers.DataSource = dt;
  }
  protected void RadAjaxManager1_AjaxRequest(object sender, AjaxRequestEventArgs e)
  {
      if (e.Argument == "Rebind")
      {
          gvCustomers.MasterTableView.SortExpressions.Clear();
          gvCustomers.MasterTableView.GroupByExpressions.Clear();
          gvCustomers.Rebind();
      }
      else if (e.Argument == "RebindAndNavigate")
      {
          gvCustomers.MasterTableView.SortExpressions.Clear();
          gvCustomers.MasterTableView.GroupByExpressions.Clear();
          gvCustomers.MasterTableView.CurrentPageIndex = gvCustomers.MasterTableView.PageCount - 1;
          gvCustomers.Rebind();
      }
 
  }


Thanks,
Jayesh Goyani
0
Jayesh Goyani
Top achievements
Rank 2
answered on 29 Oct 2013, 12:43 PM
Hello,

Not able to reproduce. I have tried with the above code snippet.

http://screencast.com/t/lEyd8U8ZUwTQ

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