?
Solved

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

Posted on 2012-03-20
3
Medium Priority
?
385 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
3 Comments
 
LVL 20

Accepted Solution

by:
BuggyCoder earned 2000 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

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
This is my first video review of Microsoft Bookings, I will be doing a part two with a bit more information, but wanted to get this out to you folks.
Sometimes it takes a new vantage point, apart from our everyday security practices, to truly see our Active Directory (AD) vulnerabilities. We get used to implementing the same techniques and checking the same areas for a breach. This pattern can re…
Suggested Courses

765 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