Monday, January 2, 2012

Show Header and Footer of GridView with an empty DataSource in C#

When the DataSource  is empty, the GridView is disappeared and we can not use the footer to add new item. In this post, I will give you the method to show Header and Footer when DataSource is empty. The tip here is to add a new blank row to DataTable used as DataSource when no data returned in our query.
                        
        protected void bindToGrid()
        {
            string connstr = "Data Source=WIN2K8; Initial Catalog=ABC;User ID=sa; Password=123";
            DataTable dt = new DataTable();
            SqlConnection conn = new SqlConnection(connstr);
            conn.Open();                                     
            string strsql = "Select * from Products";
            SqlCommand cmd = new SqlCommand(strsql, conn);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(dt);
            if (dt.Rows.Count > 0)
            {
                grid.DataSource = dt;
                grid.DataBind();
            }
            else
            {
                dt.Rows.Add(dt.NewRow());
                grid.DataSource = dt;
                grid.DataBind();
                this.grid.Rows[0].Visible = false;
            }
            conn.Close();                    
        }

The Header and Footer will be displayed with an empty data as shown in the bellow figure:

Hope this helps!

Read more:

Create a nested GridView control
Get data from SQL database and display in GridView control

 

4 comments:

raghavendra said...

Excellent Post..Thanks

Anonymous said...

GridView data binding C#

Contra a corrupção said...

Excellent Post..Thanks

SATHEESH KUMAR M.V said...

Excellent ….no words to say ……………..

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Affiliate Network Reviews