Geeks With Blogs
Bunch's Blog One day I'll have a catchy subtitle, one day
Here is one way to access a control in a GridView right after a user clicks a button to change from view to edit mode. This example shows a TextBox that gets populated with today's date. The GridView is setup like this:

<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False"
    DataKeyNames="TestID" DataSourceID="SqlDataSource1" onrowdatabound="GridView2_RowDataBound" >
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:Button ID="btnEdit" runat="server" Text="Edit" CommandName="Edit" CommandArgument='<%# Container.DataItemIndex %>' />
            </ItemTemplate>
            <EditItemTemplate>
                <asp:Button ID="btnCancel" runat="server" Text="Cancel" CommandName="Cancel" />
            </EditItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:Label ID="lblTest1" runat="server" Text='<%# BIND("TestID") %>' />
            </ItemTemplate>
            <EditItemTemplate>
                <asp:Label ID="lblTest4" runat="server" Text='<%# BIND("TestID") %>' />
            </EditItemTemplate>
        </asp:TemplateField>
            <asp:TemplateField>
            <ItemTemplate>
                <asp:Label ID="lblTest2" runat="server" Text='<%# BIND("Value1") %>' />
            </ItemTemplate>
            <EditItemTemplate>
                <asp:TextBox ID="txtTest1" runat="server" Text="test" />
            </EditItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:Label ID="lblTest3" runat="server" Text='<%# BIND("Value2") %>' />
            </ItemTemplate>
            <EditItemTemplate>
                <asp:TextBox ID="txtTest2" runat="server" />
            </EditItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

The txtTest2 TextBox is the one that we want to put today's date in. To enter that information during the switch into edit you can add the following:

 protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowState.HasFlag(DataControlRowState.Edit))
        {
            TextBox txtBox2 = (TextBox)e.Row.FindControl("txtTest2");

            txtBox2.Text = DateTime.Now.ToShortDateString();
        }
    }

The little trick lies in the DataControlRowState.Edit line. When that is true you can use the normal FindControl methods to grab the control you need. Probably not a common thing to do with a GridView but you never know.


Technorati Tags: , , Posted on Friday, December 23, 2011 11:40 AM | Back to top


Comments on this post: Finding a GridViews Edit Control

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © Bunch | Powered by: GeeksWithBlogs.net