views:

18

answers:

2

ASCX File:

<asp:datagrid runat="server" id="gridFormFields" datakeyfield="FieldID"
autogeneratecolumns="False" 
onitemcommand="gridFormFields_ItemCommand" onitemdatabound="gridFormFields_ItemDataBound">
<columns>
    <asp:templatecolumn>
        <itemtemplate>
            <asp:imagebutton runat="server" id="buttonMoveUpFormField" resourcekey="buttonMoveUpFormField"
            commandname="Item" commandargument="MoveUp" imageurl="~/images/up.gif" />
        </itemtemplate>
    </asp:templatecolumn>
    <asp:templatecolumn>
        <itemtemplate>
            <asp:imagebutton runat="server" id="buttonMoveDownFormField" resourcekey="buttonMoveDownFormField" 
            commandname="Item" commandargument="MoveDown" imageurl="~/images/dn.gif" />
        </itemtemplate>
    </asp:templatecolumn>
</columns>

Code behind:

protected void gridFormFields_ItemDataBound(object sender, DataGridItemEventArgs e)
    {
        (e.Item.FindControl("buttonMoveUpFormField") as ImageButton)
         .Visible = gridFormFields.Items.Count > 1 && e.Item.ItemIndex > 0;

        (e.Item.FindControl("buttonMoveDownFormField") as ImageButton)
         .Visible = gridFormFields.Items.Count > 1 && e.Item.ItemIndex < gridFormFields.Items.Count - 1;
    }
  • In the code behind, the Control returned by FindControl is null. Why?

  • How can I access the buttonMoveUpFormField and buttonMoveDownFormField controls?

  • From the code behind, is it possible to access controls which are declared in the ItemTemplate section of the TemplateColumn section of a DataGrid?

+1  A: 

You can certainly access the controls that are within the ItemTemplate section. I'm dealing with a similar issue. One thing that I've found is, depending what is calling your "gridFormFields_ItemDataBound", you may not have access to those controls yet.

I know that in my instance, I've got an "ItemTemplate" and an "EditItemTemplate", when I click edit, it fires an event "RowEditing" before it is actually switched to "Edit Mode", so the control will not be there yet. I do though have access to the controls in "RowUpdating" which is fired when I click save in the edit mode.

Maybe this helps? For example, your "OnDataBound" might be the event that is trying to access your controls, but you may not have access to them on databound?

Just a thought. I'll edit this if I get any further on mine.

Brett
Thanks for the hint. I suggest you try epitka's answer as it worked for me.
asmo
+1  A: 

Because you need to add code to include "Item" and "AlternatingItem" and exclude all other types, before you try to find that control.

if (e.Item.Type == ...

epitka
This worked out my problem. Thanks.
asmo