Solved

Gridview not showing headings when data table empty ASP.net 4

Posted on 2012-03-20
3
377 Views
Last Modified: 2012-03-22

Open in new window

Hi All,

I've got a bound data gridview. When there is no data present in the data table it doesn't show the column headings dispite me setting the "Show Headers when Empty" property on the page to true. the code I have is: -

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

namespace Systems
{
    public partial class Log_systemsHours : System.Web.UI.Page
    {

        DataTable  dt;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                dt = new DataTable();
                MakeDataTable();
            }
            else
            {
                dt = (DataTable)ViewState["DataTable"];
            }
            ViewState["DataTable"] = dt;
            HFLabourType.Value = Request.QueryString["LabourType"];

            if (Request.QueryString["LabourType"] == "S")
            {
                lblTitle.Text = "Log Systems Manufacturing Hours";
            }
            else if (Request.QueryString["LabourType"] == "E")
            {
                lblTitle.Text = "Log Systems Engineering Hours";
            }
            else if (Request.QueryString["LabourType"] == "T")
            {
                lblTitle.Text = "Log Manufacturing Test Hours";
            }
        }

        protected void cmdAddhours_Click(object sender, EventArgs e)
        {
            AddToDataTable();
            BindGrid();
        }

        private void MakeDataTable()
        {
            dt.Columns.Add("SalesOrder");
            dt.Columns.Add("Employee");
            dt.Columns.Add("EmployeeID");
            dt.Columns.Add("Notes");
            dt.Columns.Add("Hours");
        }



        private void AddToDataTable()
        {
            DataRow dr = dt.NewRow();
            dr["SalesOrder"] = "12345"; //cmbSalesOrder.SelectedItem.ToString();
            dr["EmployeeID"] = cmbEmployee.SelectedValue.ToString();
            dr["Employee"] = cmbEmployee.SelectedItem.ToString();
            dr["Notes"] = txtNotes.Text.ToString();
            dr["Hours"] = txtHours.Text.ToString();
            dt.Rows.Add(dr);
        }

        private void BindGrid()
        {
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }

        protected void cmdsave_Click(object sender, ImageClickEventArgs e)
        {

            if (GridView1.Rows.Count == 0)
            {

                Response.Write("<script>alert('No hours have been entered to save.')</script>");
                return;
            }

            foreach (DataRow dr2 in dt.Rows)
            {
                //how do I iterate through the columns of each row in my DataTale (dt)?
                //txtPartDesc.Text = dr2["Supplier"].ToString();
                SqlConnection conn2 = new SqlConnection(ConfigurationManager.ConnectionStrings["jConnectionString"].ConnectionString);
                conn2.Open();

                // 1. create a command object identifying
                // the stored procedure
                SqlCommand cmd2 = new SqlCommand("Systems_AddLabourHours", conn2);

                // 2. set the command object so it knows
                // to execute a stored procedure
                cmd2.CommandType = CommandType.StoredProcedure;

                // 3. add parameter to command, which
                // will be passed to the stored procedure
                cmd2.Parameters.Add(new SqlParameter("@SalesOrder", dr2["SalesOrder"].ToString()));
                cmd2.Parameters.Add(new SqlParameter("@EmployeeID", dr2["EmployeeID"].ToString()));
                cmd2.Parameters.Add(new SqlParameter("@Notes", dr2["Notes"].ToString()));
                cmd2.Parameters.Add(new SqlParameter("@Hours", dr2["hours"].ToString()));
                cmd2.Parameters.Add(new SqlParameter("@HoursType", "W"));

                // execute the command
                cmd2.ExecuteNonQuery();
                conn2.Close();
            }
        }

        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            int RowIndex = Convert.ToInt32(e.CommandArgument);
            dt.Rows.RemoveAt(RowIndex);
            BindGrid();
        }

    }
}

Best Regards
Lee
0
Comment
Question by:Codingitup
3 Comments
 
LVL 20

Accepted Solution

by:
BuggyCoder earned 500 total points
ID: 37741701
Just check for datatable Rows, if it doesn't contain any data, then just add an empty row before binding.

private void BindGrid()
        {
            if(dt.Rows.Count==0)
           {
                  dt.Rows.Add(dt.NewRow());  
            }
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }

Open in new window

0
 
LVL 5

Expert Comment

by:Vishal Kedar
ID: 37742012
Add below property in aspx code

<asp:GridView ShowHeaderWhenEmpty="True"/>
0
 
LVL 22

Expert Comment

by:Mrunal
ID: 37742363
Simple logic is:
1. add emptydatatemplate in aspx of gridview.

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.emptydatatemplate.aspx

2. even if data is null, always call method, GridView1.DataBind();

that's it. It will show empty template when no data binded...
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

A quick way to get a menu to work on our website, is using the Menu control and assign it to a web.sitemap using SiteMapDataSource. Example of web.sitemap file: (CODE) Sample code to add to the page menu: (CODE) Running the application, we wi…
Problem Hi all,    While many today have fast Internet connection, there are many still who do not, or are connecting through devices with a slower connect, so light web pages and fast load times are still popular.    If your ASP.NET page …
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.
Concerto provides fully managed cloud services and the expertise to provide an easy and reliable route to the cloud. Our best-in-class solutions help you address the toughest IT challenges, find new efficiencies and deliver the best application expe…

948 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

24 Experts available now in Live!

Get 1:1 Help Now