Click here to Skip to main content
Click here to Skip to main content

Access Controls from ASP.NET GridView EmptyDataTemplate using FindControl Method

By , 20 Jul 2012
 

Introduction

The empty data row is displayed in a GridView control when the data source that is bound to the control does not contain any records. You can define your own custom user interface (UI) for the empty data row by using the EmptyDataTemplate property. Below I'm giving a sample screen where it's displaying "No Records Found" message if the GridView control does not contain any records and at the same time we can capture new employee information also. Please click here to check the full article.

Background

This code is based on my another article in ASP.NET GridView Insert, Update and Delete, please click here to check the same. Here I'm explaining the code only related to EmptyDataTemplate.

Using the Code

HTML

Below, I have given the EmptyDataTemplete ASPX code for the Gridview, I have created a <table> and added the "No Records Found" message in a <tr> and in another <tr> I have given all controls that will be used to enter Employee information in-case of no existing records.

<EmptyDataTemplate>
    <table class="grid" cellspacing="0" rules="all" 
    border="1" id="gvEG" style="border-collapse: collapse;">
        <tr>
            <th align="left" scope="col">
                Employee Code
            </th>
            <th align="left" scope="col">
                Name
            </th>
            <th align="left" scope="col">
                Department
            </th>
            <th align="left" scope="col">
                Group
            </th>
            <th align="left" scope="col">
                Email
            </th>
            <th scope="col">
                Ative
            </th>
            <th align="left" scope="col">
                Edit
            </th>
            <th scope="col">
                Delete
            </th>
        </tr>
        <tr class="gridRow">
            <td colspan="8">
                No Records found...
            </td>
        </tr>
        <tr class="gridFooterRow">
            <td>
                <asp:TextBox ID="txtEmployeeCode" runat="server" 
                MaxLength="6" Width="50px"></asp:TextBox>
            </td>
            <td>
                <asp:TextBox ID="txtEmployeeName" runat="server" 
                Width="90px"></asp:TextBox>
            </td>
            <td>
                <asp:DropDownList ID="ddlDepartment" runat="server" 
                DataTextField="Name" DataValueField="Id">
                </asp:DropDownList>
            </td>
            <td>
                <asp:DropDownList ID="ddlEmployeeGroup" runat="server">
                    <asp:ListItem Text="User" Value="User" 
                    Selected="True"></asp:ListItem>
                    <asp:ListItem Text="Admin" Value="Admin"></asp:ListItem>
                    <asp:ListItem Text="Super User" 
                    Value="Super User"></asp:ListItem>
                </asp:DropDownList>
            </td>
            <td>
                <asp:TextBox ID="txtEmail" runat="server" Width="100px" />
            </td>
            <td>
                <asp:CheckBox ID="chkActive" runat="server" />
            </td>
            <td colspan="2" align="justify" valign="middle">
                <asp:LinkButton ID="lnkAdd" runat="server" 
                CausesValidation="false" CommandName="emptyInsert"
                    Text="Insert"></asp:LinkButton>
            </td>
        </tr>
    </table>
</EmptyDataTemplate> 

Code-Behind

In RowCommand, I capture the Link Button click from the EmpltyDataTemlate. Here, we check the commandName and if it has the value"emptyInsert", then create the object of EmployeeInfo.

We can get the EmptyDateTemplate reference in code-behind by the below given code (gvEG is my GridView name).

GridViewRow emptyRow = gvEG.Controls[0].Controls[0] as GridViewRow; 

Once we have the GridViewRow, then we can use the below code to find the controls:

emptyRow.FindControl("txtEmployeeCode")  
protected void gvEG_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName.Equals("emptyInsert"))
    {
        EmployeeInfo eInfo = new EmployeeInfo();
        GridViewRow emptyRow = gvEG.Controls[0].Controls[0] as GridViewRow;
        eInfo.EmployeeCode = Convert.ToString
        (((TextBox)emptyRow.FindControl("txtEmployeeCode")).Text);
        eInfo.EmployeeName = ((TextBox)emptyRow.FindControl("txtEmployeeName")).Text;
        eInfo.DepartmentId = Convert.ToInt32(((DropDownList)
        emptyRow.FindControl("ddlDepartment")).SelectedValue);
        eInfo.DepartmentName = Convert.ToString(((DropDownList)
        emptyRow.FindControl("ddlDepartment")).SelectedItem.Text);
        eInfo.EmployeeGroup = ((DropDownList)emptyRow.FindControl
        ("ddlEmployeeGroup")).SelectedValue;
        eInfo.Email = ((TextBox)emptyRow.FindControl("txtEmail")).Text;
        eInfo.isActive = ((CheckBox)emptyRow.FindControl("chkActive")).Checked;
        new mainSQL().insertEmployeeInfo(eInfo);
        FillEmployeeGrid();
    }
} 

Summary

I hope this tip helped you to understand how to find controls from EmptyDataTemplate of ASP.NET GridView. Please check the full article from this link at ASP.NET GridView Insert, Update and Delete.

Please give your valuable suggestions and feedback for further improvements. Thanks for reading.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Shemeer NS
Software Developer (Senior)
India India
Member
Technology Specialist | CodeProject MVP | Author | Geek | Netizen | Husband | ChessPlayer
 
Most of my articles are listed on top 5 of the respective 'Best articles of the month' and some of my articles are published on ASP.NET WebSite's Article of the Day section.
 
Check my contributions in Visual Studio Gallery and Code Project

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5membereparthibanmca22 Apr '13 - 18:46 
i have looking this exact solution for wasting time to search this result.
Questiongetting null values on accessing EmptyDataTemplate controlsmemberMember 875347024 Nov '12 - 10:08 
i getting null values when i accessing EmptyDataTemplate controls.
i using same code as you show.
AnswerRe: getting null values on accessing EmptyDataTemplate controlsmemberShemeer NS25 Nov '12 - 8:11 
check this link also
Insert, Update, Delete in ASP.NET Gridview, DataSource as SQL Server, MS Access (mdb/accdb), XML and Framework as 2.0 / 3.0 / 3.5 / 4.0 (VS 2005/2008/2010)[^]
Questionrow is not getting delete in gridviewmemberAnkit Saxena8 Nov '12 - 17:50 
i am trying to delete row in my gridview and it is showing no error but still row is not getting delete....plz help to get me rid of this...my code is as follows
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
myobj.myconnection();
SqlCommand cmd=new SqlCommand("delete from state where ID=@ID", myobj.sqlcon);
 
cmd.ExecuteNonQuery();
Response.Write("data deleted");
GridView1.DataBind();
 
}
AnswerRe: row is not getting delete in gridviewmemberShemeer NS9 Nov '12 - 4:23 
Quote:
SqlCommand cmd=new SqlCommand("delete from state where ID=@ID", myobj.sqlcon);

 
You have not passed the value for @ID
Questionincreasing Gridviews Rows without inserting into Databasememberanglo007228 Oct '12 - 11:54 
i just changed datasource in gvEG_RowCommand event
eList.Add(eInfo); // EmployeeInfo eInfo = null; eInfo = new EmployeeInfo();
gvEG.DataSource = eList; // List<EmployeeInfo> eList = new List<EmployeeInfo>();
gvEG.DataBind();
it`s working well with "emptyInsert" Command Name only for first time without inserting into database, but with "Insert" the row seem to be updated with new values.and here i want to add the new row with new values
how can i add the new row after inserting values?
how do i use DataTable and DataRow and then add NewRow(); for gvEG (GridView)?
QuestionFind Control inside the Gridview On Page loadmemberkuldeep158624 Sep '12 - 0:26 
very good post. but sir i wanna find control on page Load Event for fill value from Quiry string.so please Help me.
 
if (Request.QueryString["accName"] != null)
           {
               foreach (GridViewRow grow in grd_vouchrdetails.Rows)
               {
                   TextBox txt_aName = (TextBox)grow.FindControl("txt_accoHead");
                   txt_aName.Text = Convert.ToString(Request.QueryString["accName"]);
               }
           }
but i am not find text box inside the Grid view
AnswerRe: Find Control inside the Gridview On Page loadmemberShemeer NS24 Sep '12 - 1:56 
Is it going inside the foreach loop..
I doubt that the gridview controls row count is zero due to non binding of records, make sure you have assigned the datasource to the gridview.
GeneralRe: Find Control inside the Gridview On Page loadmemberkuldeep158624 Sep '12 - 2:57 
Thanx for Reply Sir.
Actully my problem is
I have GridView With Item Template Some textboxs and Dropdown list.
ihave a Image inside the Gridview itemtemplate when Click On Image its Open Popup Window new page With Gridview.after That When Click any Record of Popupwindow Gridview Column then Fill in parent Gridview item template TexboxBox and Popup Close.
GeneralRe: Find Control inside the Gridview On Page loadmemberanglo007228 Oct '12 - 13:22 
foreach (GridViewRow row in GridView1.Rows)
{  
   for (int i = 0; i <= GridView1.Rows.Count; i++)
   {
      Image img = GridView1.Rows[row.RowIndex].FindControl("image1") as Image;
      if (img.ClientID == "image"+i)
                    {
                        // do something like below
                        img.ImageUrl = "";
                    }
   }
}
you can use the javascript onClick event on imgae, but why not imagebutton with postbackurl?
and if you are trying to find the control of Nested Gridview (another gridview inside girdview) why not try Gridview.parent.parent
GeneralMy vote of 5memberfquezada11 Sep '12 - 6:20 
Very nice and useful
GeneralMy vote of 5memberMember 343557620 Jul '12 - 19:39 
very useful

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130513.1 | Last Updated 20 Jul 2012
Article Copyright 2012 by Shemeer NS
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid