Solved

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

Posted on 2012-03-20
3
372 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
Comment Utility
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
Comment Utility
Add below property in aspx code

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

Expert Comment

by:Mrunal
Comment Utility
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

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…
This tutorial demonstrates a quick way of adding group price to multiple Magento products.

762 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

15 Experts available now in Live!

Get 1:1 Help Now