Solved

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

Posted on 2012-03-20
3
380 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

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone 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

User art_snob (http://www.experts-exchange.com/M_6114203.html) encountered strange behavior of Android Web browser on his Mobile Web site. It took a while to find the true cause. It happens so, that the Android Web browser (at least up to OS ver. 2.…
Introduction This article shows how to use the open source plupload control to upload multiple images. The images are resized on the client side before uploading and the upload is done in chunks. Background I had to provide a way for user…
Although Jacob Bernoulli (1654-1705) has been credited as the creator of "Binomial Distribution Table", Gottfried Leibniz (1646-1716) did his dissertation on the subject in 1666; Leibniz you may recall is the co-inventor of "Calculus" and beat Isaac…

809 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