Few days ago I received an email from a reader asking how to access the value of the control contained inside the EmptyDataTemplate of the GridView control. As, you might already know that EmptyDataTemplate is used when there are no records to display. Sometimes you want to give the user an option to add a new item by providing controls inside the EmptyDataTemplate.
<asp:GridView ID="gvCategories" AutoGenerateColumns="false" runat="server" onrowcommand="gvCategories_RowCommand"
>
<EmptyDataTemplate>
<asp:TextBox ID="txtCategoryName" runat="server" />
<asp:Button ID="Btn_AddNewItem" runat="server" CommandName="AddNewItem" Text="Add" />
</EmptyDataTemplate>
</asp:GridView>
The above GridView has a TextBox and a Button control inside the EmptyDataTemplate. Now, when the button is clicked we want to access the value inside the TextBox.
protected void gvCategories_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("AddNewItem"))
{
GridViewRow row = (GridViewRow)((e.CommandSource as Button).NamingContainer);
string categoryName = (row.FindControl("txtCategoryName") as TextBox).Text;
Response.Write(categoryName);
}
}
The line (GridViewRow)((e.CommandSource as Button).NamingContainer); is responsible for extracting the GridViewRow out of the GridView control. Once, you have the GridViewRow simply use the FindControl method to find the control and access the value you want.