7 Replies - 9246 Views - Last Post: 17 November 2012 - 10:48 PM Rate Topic: -----

#1 gngr  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 15-March 12

Hiding empty GridView columns

Posted 28 March 2012 - 09:33 AM

Hi
Iím trying to hide empty gridview columns. My C# books donít talk about doing this so Iíve done a bit of googling and tried the following
     Results.DataSource = myDATAview;
            Results.DataBind();
            //if (Results.Columns == null)
           // if (myDATAset.Tables[0] == null)
         // if   (Results.Columns.Count > 0)
            if (Results.Columns.Equals(""))

           {
              Results.Columns[0].Visible = false;
           } 

None of this worked or threw any errors.
Am I on the right track or way off?

Is This A Good Question/Topic? 0
  • +

Replies To: Hiding empty GridView columns

#2 raziel_  Icon User is offline

  • Like a lollipop
  • member icon

Reputation: 464
  • View blog
  • Posts: 4,255
  • Joined: 25-March 09

Re: Hiding empty GridView columns

Posted 28 March 2012 - 09:48 AM

did you try debugging? i`m pretty sure that the code in your if is never executed
also you want to hide the whole column where there is no data in any row in the grid for that column? then loop all your rows check if there is data in any row in that column and if not then hide it.

This post has been edited by raziel_: 28 March 2012 - 09:50 AM

Was This Post Helpful? 0
  • +
  • -

#3 gngr  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 15-March 12

Re: Hiding empty GridView columns

Posted 28 March 2012 - 03:30 PM

Hey thanks for your reply. When I debug everything works but its still displaying the empty columns, no errors or warnings appear.

I've done a bit more googling based on what you've suggested and I've replaced the previous if statements with
        foreach(GridViewRow row in this.Results.Rows)
           {
               if (row.Equals(""))
               {
                   Results.Columns[0].Visible = false;
               }

               }


Debugged and the same thing happens, everything else works, no warning, no errors but I've still got empty columns
Was This Post Helpful? 0
  • +
  • -

#4 BigR1983  Icon User is offline

  • D.I.C Head

Reputation: 57
  • View blog
  • Posts: 221
  • Joined: 12-April 10

Re: Hiding empty GridView columns

Posted 28 March 2012 - 03:49 PM

in the foreach, you are iterating over a GridViewRow (an object) so doing a string compare to "" will never fire (i think :))

From what I found on google, you could explicitly declare your columns when you get the data in

http://stackoverflow...h-will-be-empty

or key off the GridView.Rows[0].Cells.Count property
http://stackoverflow...-column-by-code

Hope that helps :)
Was This Post Helpful? 0
  • +
  • -

#5 gngr  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 15-March 12

Re: Hiding empty GridView columns

Posted 29 March 2012 - 04:56 AM

Still no luck
I'm so confused! :unsure:
Was This Post Helpful? 0
  • +
  • -

#6 eclipsed4utoo  Icon User is offline

  • Not Your Ordinary Programmer
  • member icon

Reputation: 1524
  • View blog
  • Posts: 5,960
  • Joined: 21-March 08

Re: Hiding empty GridView columns

Posted 29 March 2012 - 05:52 AM

I would probably use the RowDataBound event and check for blank there.

http://msdn.microsof...wdatabound.aspx
Was This Post Helpful? 0
  • +
  • -

#7 Algernoncharles  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 16-November 12

Re: Hiding empty GridView columns

Posted 16 November 2012 - 12:47 AM

No sense in showing a competely blank column. how to make a GridView column invisible if every cell in that column is empty? dapfor. com
Was This Post Helpful? 0
  • +
  • -

#8 Nakor  Icon User is offline

  • Professional Lurker
  • member icon

Reputation: 444
  • View blog
  • Posts: 1,492
  • Joined: 28-April 09

Re: Hiding empty GridView columns

Posted 17 November 2012 - 10:48 PM

Well, one method would be to set the Autogeneratecolumns property to false, but not define any columns in the .aspx page. Instead, define your columns programmatically in the codebehind. It's a little more work and requires an extra trip to the database, but here's how you could do it.

First, a quick side note: I am using Entity Framework and the System.Linq.Dynamic namespace which can be added to your project using Nuget if you search for Dynamic Linq.

First thing I do is override the OnInit page method. During this event I initialize my data context and assign the PageIndexChanging and Sorting event handlers for my gridview.

        protected override void OnInit(EventArgs e)
        {
            this.context = new NorthwindEntities();

            this.GridView1.PageIndexChanging += this.GridView1_PageIndexChanging;
            this.GridView1.Sorting += GridView1_Sorting;
            base.OnInit(e);
        }



I also create a couple of page properties to save the current sort column and sort direction.

        public string GridSortColumn
        {
            get
            {
                object temp = ViewState["SortColumn"];
                return temp == null ? "CustomerID" : (string)temp;
            }
            set { ViewState["SortColumn"] = value; }
        }

        public string GridSortDirection
        {
            get
            {
                object temp = ViewState["SortDirection"];
                return temp == null ? "Ascending" : (string)temp;
            }
            set { ViewState["SortDirection"] = value; }
        }



Next, I go ahead and define my paging and sorting events.

protected void Page_Load(object sender, EventArgs e)
{
    this.LoadGridview();
}

void GridView1_Sorting(object sender, GridViewSortEventArgs e)
        {
            if (GridSortColumn == e.SortExpression)
            {
                if (GridSortDirection == SortDirection.Ascending.ToString())
                {
                    this.GridSortDirection = SortDirection.Descending.ToString();
                }
                else
                {
                    this.GridSortDirection = SortDirection.Ascending.ToString();
                }
            }
            else
            {
                GridSortColumn = e.SortExpression;
                GridSortDirection = SortDirection.Ascending.ToString();
            }

            this.LoadGridview();
        }

        void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GridView1.PageIndex = e.NewPageIndex;
            this.LoadGridview();
        }



As you can see, I have a method named LoadGridview(). This method, as the name implies, is used to load the data into the gridview. It will also call another method that will determine which columns to add to the gridview.

private void LoadGridview()
        {            
            SetGridviewColumns();

            GridView1.DataSource = this.context.Customers.Select(c =>
                new CustomerModel
                {
                    CustomerID = c.CustomerID,
                    ContactName = c.ContactName,
                    CompanyName = c.CompanyName,
                    Phone = c.Phone,
                    Fax = c.Fax,
                    Region = c.Region
                })
                .OrderBy(GridSortColumn + " " + GridSortDirection)
                .ToList();
            
            GridView1.DataBind();
        }



As you can see, I have a method being called that is named SetGridviewColumns. The data that I am pulling from the database is also getting converted into a ViewModel named CustomerModel. The importance of this is that it allows me to define a subset of columns that I want to be available while still having the data be strongly typed rather than using an anonymous type. The importance of having the data be strongly typed will be evident in the code for the SetGridviewColumns method.

        private void SetGridviewColumns()
        {
            GridView1.Columns.Clear();
            var customers = (from c in this.context.Customers
                             select new CustomerModel
                             {
                                 CustomerID = c.CustomerID, 
                                 ContactName = c.ContactName, 
                                 CompanyName = c.CompanyName, 
                                 Phone = c.Phone,
                                 Fax = c.Fax,
                                 Region = c.Region
                             })
                             // Requires the System.Linq.Dynamic namespace
                             .OrderBy(this.GridSortColumn + " " + this.GridSortDirection)
                             .Skip(GridView1.PageIndex)
                             .Take(GridView1.PageSize);

            var properties = typeof(CustomerModel).GetProperties();

            foreach (var property in properties)
            {
                bool addColumn = false;

                foreach (var customer in customers)
                {
                    if (customer != null)
                    {
                        var cellValue = property.GetValue(customer, null);
                        if (cellValue != null && !string.IsNullOrWhiteSpace(cellValue.ToString().Trim()))
                        {
                            addColumn = true;
                            break;
                        }
                    }
                }

                if (addColumn)
                {
                    BoundField column = new BoundField();
                    column.DataField = property.Name;
                    column.HeaderText = property.Name;
                    column.SortExpression = property.Name;

                    if (!GridView1.Columns.Contains(column))
                    {
                        GridView1.Columns.Add(column);
                    }
                }
            }
        }



The first thing the SetGridviewColumns method does is clear the current columns from the gridview. It then pulls the exact data that is going to be displayed. It does this by applying the current sort column and sort direction and then uses the page index and page size properties of the gridview. var properties = typeof(CustomerModel).GetProperties(); gets the properties of the ViewModel that is used to define the desired columns. The code then loops through each row of the current data and checks that each property in that row contains data. If any row for that specific property contains data then the code adds a column to the gridview, otherwise no column is added.

This post has been edited by Nakor: 17 November 2012 - 10:51 PM

Was This Post Helpful? 1
  • +
  • -

Page 1 of 1