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

[Solved] ItemCommand - Why is my ItemIndex always zero?

6 Answers 675 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Steve Y
Top achievements
Rank 2
Steve Y asked on 05 May 2009, 04:56 PM
I have a need to create a pdf file for a selected row in a grid which I then download to the client pc. I have the pdf creation working fine in code behind. I've got it triggered from a button on the command row. The button click downloads a pdf file based on the selected row in the grid. The grid is ajaxified using a RadAjaxPanel and, in order to perform the pdf file download, I disable the ajax call on click of the button, and then do a Response.BinaryWrite(pdfBytes) of the pdf data, which basically is then doing a regular postback. I get the pdf file transfered correctly to the client pc with a save as/open diaglog box.

Now I want to do the same thing but from a button in each row of the grid. I have a grid with a standard linq datasource. I have a gridbuttoncolumn with an imagebutton which has a command of Print. I've hooked the client OnCommand to some javascript to cancel the ajax call. I've hooked the server side OnItemCommand to a c# handler and everything fires ok.

My problem is that the e.item.itemIndex value is always zero regardless of what row button I click. All my row data seems to be in place because inside the OnItemCommand if I supply a hard coded index to a GetDataKeyValues, I get the data key correctly. Here are the two samples. The first only ever gives me the data key of item zero because e.Item.ItemIndex is always 0.

protected void RadGridLetters_ItemCommand(object source, Telerik.Web.UI.GridCommandEventArgs e) 
    { 
        if (e.CommandName == "Print") 
        { 
            int letterId = (int)e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["LetterId"];   
            CreatePDF(letterId); 
        } 
    }  

This one proves the data is there because I get the key value for the 7th row (indexed from 0).
protected void RadGridLetters_ItemCommand(object source, Telerik.Web.UI.GridCommandEventArgs e) 
    { 
        if (e.CommandName == "Print") 
        { 
            int letterId = (int)e.Item.OwnerTableView.DataKeyValues[6]["LetterId"];   
            CreatePDF(letterId); 
        } 
    }  


Why is my ItemIndex always Zero?

Thanks,
Steve (pulling my hair out...)





btw. Here's some code extracted from my app to give you more context.

aspx.
<Telerik:RadAjaxPanel ID="RadAjaxPanelLetters" runat="server" LoadingPanelID="RadAjaxLoadingPanel2" ClientEvents-OnRequestStart="onRequestStartLetters"
<telerik:RadGrid ID="RadGridLetters" runat="server" GridLines="None" EnableEmbeddedSkins="false" Skin="RealMax" 
        AllowAutomaticInserts="True" AllowAutomaticUpdates="True" AllowAutomaticDeletes="true"  
        DataSourceID="LinqDS_Letters" OnItemCommand="RadGridLetters_ItemCommand"  
        AllowPaging="True" AllowSorting="True" EnableHeaderContextMenu="True" 
        AllowFilteringByColumn="True" > 
    <ClientSettings EnableRowHoverStyle="true" > 
        <ClientEvents OnRowContextMenu="RowContextMenu" OnRowMouseOut="rowMouseOut" OnRowMouseOver="rowMouseOver" OnPopUpShowing="PopUpCentered" OnCommand="GridCommand" ></ClientEvents
        <Selecting AllowRowSelect="true" /> 
    </ClientSettings> 
    <HeaderContextMenu Skin="Office2007" EnableTheming="True"
        <CollapseAnimation Type="OutQuint" Duration="200"></CollapseAnimation> 
    </HeaderContextMenu> 
 
    <PagerStyle Mode="NextPrevNumericAndAdvanced" AlwaysVisible="false" /> 
    <MasterTableView AutoGenerateColumns="False" CommandItemDisplay="Top"  
            DataKeyNames="LetterId" DataSourceID="LinqDS_Letters" EditMode="EditForms"
    <RowIndicatorColumn> 
        <HeaderStyle Width="20px"></HeaderStyle> 
    </RowIndicatorColumn> 
    <ExpandCollapseColumn> 
        <HeaderStyle Width="20px"></HeaderStyle> 
    </ExpandCollapseColumn> 
    <ItemStyle CssClass="RowMouseOut" /> 
    <AlternatingItemStyle CssClass="RowMouseOut" /> 
    <Columns> 
        <telerik:GridEditCommandColumn EditImageUrl="~/Images/Buttons/edit.gif"  
            ButtonType="ImageButton" CancelImageUrl="~/Images/Buttons/cancel.png"  
            Resizable="False"
            <HeaderStyle Width="16px" /> 
            <ItemStyle CssClass="CommandColumn" /> 
        </telerik:GridEditCommandColumn> 
        <Telerik:GridButtonColumn ButtonType="ImageButton" ImageUrl="~/Images/Buttons/printer.png" Text="Print" CommandName="Print" > 
            <HeaderStyle Width="16px" /> 
            <ItemStyle CssClass="CommandColumn" /> 
        </Telerik:GridButtonColumn> 
 
... etc 

javascript:
var cancelAjaxLetters = false
 
function GridCommand(sender, args) { 
        if (args.get_commandName() == "Print") cancelAjaxLetters = true
    } 
 
function onRequestStartLetters(ajaxManager, eventArgs) { 
    if (cancelAjaxLetters) { 
        //alert("disabling Ajax"); 
        eventArgs.EnableAjax = false
    } 
 
    cancelAjaxLetters = false

c#
 protected void RadGridLetters_ItemCommand(object source, Telerik.Web.UI.GridCommandEventArgs e) 
    { 
        if (e.CommandName == "Print"
        { 
            int letterId = (int)e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["LetterId"];   
            CreatePDF(letterId); 
        } 
    }  






6 Answers, 1 is accepted

Sort by
0
Shinu
Top achievements
Rank 2
answered on 06 May 2009, 05:29 AM
Hi Steve,

Can you try accessing the DataKeyValue as shown below and see whether it is working.

CS:
 
  protected void RadGrid1_ItemCommand(object source, GridCommandEventArgs e) 
    { 
        if (e.CommandName == "Print"
        { 
            GridDataItem item = (GridDataItem)e.Item; 
            int letterId = (int)item.GetDataKeyValue("LetterId"); 
            CreatePDF(letterId); 
        }  
    } 


Shinu
0
Steve Y
Top achievements
Rank 2
answered on 06 May 2009, 07:01 AM
Thanks for the suggestion Shinu but it's still not working the way I expect.

It seems the passed-in griddataitem is the first row in the grid (i.e. 0). Your code returns the correct datakeyitem for row 0, but I clicked on a button from row 6 or 5 or ?, and I still get a result that indicates row 0 has been selected !!

Where am I going wrong?

Thanks, Steve
0
Nikolay Rusev
Telerik team
answered on 08 May 2009, 08:01 AM
Hello Steve,

Science you have client OnCommand handler attached your server ItemCommand is always fired by first item in Items collection. This behavior appear only when you have custom CommandName/CommandArguments set.

To get real Item on server ItemCommand event you can use the code below:
protected void RadGridLetters_ItemCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)  
    {  
        if (e.CommandName == "Print")  
        {  
            GridDataItem item = RadGridLetters.Items[e.CommandArgument.ToString()];   
            int letterId = (int)item.GetDataKeyValue("LetterId");   
            CreatePDF(letterId);  
        }  
    }  


Best wishes,
Nikolay
the Telerik team

Instantly find answers to your questions on the new Telerik Support Portal.
Check out the tips for optimizing your support resource searches.
0
nestur
Top achievements
Rank 1
answered on 25 Jun 2009, 03:49 PM
I have the same problem, but none of the suggestions helped me. I have a custom CommandName as a RadToolBarButton in a RadGrids CommandItemTemplate. I also use some ClientEvents on the grid but not Client OnItemCommand.
I cannot access DataKeyValue in ItemCommand handler.
MyItems.aspx
<telerik:RadGrid ID="gridItemsList" runat="server" Skin="Default" AutoGenerateColumns="False" Width="100%" Height="100%" AllowPaging="true" GridLines="None" BorderWidth="0"   
        AllowFilteringByColumn="True" AllowSorting="True" ShowStatusBar="false" ShowGroupPanel="false" Style="outline: none"   
         OnNeedDataSource="gridItemList_NeedDataSource" OnItemCommand="gridItemsList_ItemCommand" OnColumnCreating="gridItemsList_ColumnCreating" OnItemDataBound="gridItemsList_ItemDataBound">  
            <ClientSettings Selecting-AllowRowSelect="true" EnablePostBackOnRowClick="false">  
                <Selecting AllowRowSelect="True" /> 
                <Scrolling AllowScroll="false" UseStaticHeaders="false" /> 
                <ClientEvents OnRowDblClick="OnRowDblClick"/>  
                <ClientEvents OnRowSelected="OnGridRowSelected"/>  
            </ClientSettings> 
            <PagerStyle CssClass="CustomGridPager" Height="28px" Mode="NumericPages" Position="Top">  
            </PagerStyle> 
            <MasterTableView AllowFilteringByColumn="True" CommandItemDisplay="Top" DataKeyNames="ITEMS_ID" PageSize="15">  
                <CommandItemTemplate> 
                    <telerik:RadToolBar ID="RadToolBar1" runat="server" OnButtonClick="RadToolBar1_ButtonClick">  
                        <Items> 
                            <telerik:RadToolBarButton runat="server" Text="New" CommandName="NewItem" ImageUrl="~/RadControls/Grid/Skins/Default/AddRecord.gif"></telerik:RadToolBarButton> 
                            <telerik:RadToolBarButton runat="server" Text="Edit" CommandName="EditItem" ImageUrl="~/RadControls/Grid/Skins/Edit.gif"></telerik:RadToolBarButton> 
                            <telerik:RadToolBarButton runat="server" Text="Clear Filters" CommandName="RebindGrid" ImageUrl="~/RadControls/Grid/Skins/Refresh.gif"></telerik:RadToolBarButton> 
                            <telerik:RadToolBarButton> 
                                <ItemTemplate> 
                                    <div style="padding-left:200px">  
                                        <asp:Label ID="comboLabel" runat="server" Text="View:"></asp:Label> 
                                        <telerik:RadComboBox runat="server" ID="comboViewBy" Height="80px" AutoPostBack="true"    
                                        OnClientSelectedIndexChanged="onSelectedIndexChanged" OnSelectedIndexChanged="comboViewBy_SelectedIndexChanged">  
                                            <Items> 
                                                <telerik:RadComboBoxItem runat="server" Value="1" Text="Active Items" /> 
                                                <telerik:RadComboBoxItem runat="server" Value="2" Text="My Items" /> 
                                                <telerik:RadComboBoxItem runat="server" Value="3" Text="All Items" /> 
                                                <telerik:RadComboBoxItem runat="server" Value="4" Text="Archived Items" /> 
                                            </Items> 
                                        </telerik:RadComboBox> 
                                    </div> 
                                </ItemTemplate> 
                            </telerik:RadToolBarButton> 
                        </Items> 
                    </telerik:RadToolBar> 
                </CommandItemTemplate> 

Javascript:
 
function OnGridRowSelected(sender, args) {  
            toolbar.findButtonByCommandName("EditItem").enable();  
        }  
 
function OnRowDblClick(sender, args) {  
            var id = args.getDataKeyValue("ITEMS_ID");  
            window.open(Details.aspx?id=' + id, '_blank', 'top=100, left=100height=740width=950status=nomenubar=noresizable=noscrollbars=yestoolbar=nolocation=nodirectories=no');  
        } 



MyItems.aspx.cs:
public void gridItemsList_ItemCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)  
    {  
        if (e.CommandName == "NewItem")  
        {  
            try  
            {  
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Script", "window.open('CreateItem.aspx', '_blank', 'top=100left=100height=740width=780status=nomenubar=noresizable=yesscrollbars=yestoolbar=nolocation=yesdirectories=no');", true);  
                  
            }  
            catch  
            {  
                Response.Write("Error creating item.");  
            }  
        }   
        if (e.CommandName == "EditItem")  
        {  
            GridDataItem item = gridItemsList.Items[e.CommandArgument.ToString()];  
            //string id = e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["ITEMS_ID"].ToString();  
              
            //GridDataItem item = e.Item as GridDataItem;  
            //GridDataItem item = (GridDataItem)e.Item;  
 
            string id = item.GetDataKeyValue("ITEMS_ID").ToString();  
              
            try  
            {  
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Script", "window.open('Edit.aspx?id=" + id + "', '_blank', 'top=100, left=100height=740width=780status=nomenubar=noresizable=yesscrollbars=yestoolbar=nolocation=yesdirectories=no');", true);  
                  
            }  
            catch  
            {  
                Response.Write("Error edit item.");  
            }  
        }  
    } 

e.CommandArgument return -1
e.Item.ItemIndex return -1
cannot convert GridCommandItem to GridDataItem

I`ve tried several approaches with no luck.
How do I access keyValue or DataKeyValue (ITEM_ID)?
0
Nikolay Rusev
Telerik team
answered on 30 Jun 2009, 11:55 AM
Hello Roy,

GridCommandItem inherits from GridItem and it does not have GetDataKeyValue method that extracts values from item. Only items that inherit from GridDataItem does and the GridDataItem itself.

All the best,
Nikolay
the Telerik team

Instantly find answers to your questions on the new Telerik Support Portal.
Check out the tips for optimizing your support resource searches.
0
nestur
Top achievements
Rank 1
answered on 30 Jun 2009, 12:36 PM
Hi and thank you for the response.
I can use this: 

GridDataItem

 

dataItem = gridItemsList.SelectedItems[0] as GridDataItem;

 

 

 

string id = dataItem.GetDataKeyValue("ITEMS_ID").ToString();

 

 

 

Thanks
Roy

Tags
Grid
Asked by
Steve Y
Top achievements
Rank 2
Answers by
Shinu
Top achievements
Rank 2
Steve Y
Top achievements
Rank 2
Nikolay Rusev
Telerik team
nestur
Top achievements
Rank 1
Share this question
or