GridView with Arrows

Quick Tip: Handy Sort Arrows in your GridView Without CSS or Graphics

GridView with Arrows

Click image for larger view.

The nice thing about the GridView in .Net is that there is a plethora of built in controls that simply need enabling. One of them is Sorting. Simply set the AllowSorting property to “true” in your and then make sure to write up some code for the Sorting event to adjust your data source, and you’re set.

However, one tricky thing to work with is providing a friendly way to indicate which field is being sorted, and in which direction. I’ve found a simple trick that uses no CSS or images whatsoever. Continue reading

Soup to Nuts: Exporting a GridView to Excel

Excel spreadsheets are a subtle form of currency in LOB and other environments. If you can get some data off the screen and into a spreadsheet to an Excel guru, they will love you for life and can do some amazing things with the data. In the ASP.Net WebForms world, GridViews still run rampant. They are easy to configure, easy to extend to include update/edit/delete controls, and provide a nice way to interact with data in a common interface.

Making these two items work together has been a little daunting in the past. Interfacing with the GridView wasn’t the issue, it was generating an Excel document. You could easily generate a CSV file with the data needed, but that doesn’t allow you to generate a header and potentially format some key cells in the spreadsheet. There are the Interop libraries, but these are older COM wrappers and are generally frowned upon with .Net apps. Visual Studio Tools for Office (VSTO) is a robust library for working with all of the Office document types, but it also requires Office on the system to generate the objects fully.

I recently stumbled upon a new library, called NPOI, which makes this entire process quick and painless. The library isn’t terribly new. It is a port of Apache’s POI library, which is a Java library used create and read Office documents. The POI library has been around a while and is well written, so getting the .Net version of it puts you ahead, even for its 1.2.3 release.

The example package you can download has some great samples and its really simple to iterate through the row/column structure of the document you’re creating. Since the GridView is equally easy to interate through its row/column structure, I was able to tap into an existing web application and create a basic spreadsheet in about 20. The code is as simple as this:

DocInfo = PropertySetFactory.CreateDocumentSummaryInformation();
DocInfo.Company = "Dillie-O Digital";
Workbook.DocumentSummaryInformation = DocInfo;

SummaryInfo = PropertySetFactory.CreateSummaryInformation();
SummaryInfo.Subject = "Soup to Nuts GridView Export Example";
Workbook.SummaryInformation = SummaryInfo;

DataSheet = Workbook.CreateSheet("Employees");

for(int i = 0; i <= GridData.Rows.Count - 1; i++)
{
   CurrRow = DataSheet.CreateRow(i);

   for(int j = 0; j <= GridData.Rows[i].Cells.Count - 1; j++)
   {
      if(!IgnoreColumns.Contains(j))
      {
         CurrCell = CurrRow.CreateCell(i);
         CurrCell.SetCellValue(GridData.Rows[i].Cells[j].Text);
      }
   }
}

ResultStream = new FileStream(EndPath, FileMode.Create);
Workbook.Write(ResultStream);
ResultStream.Close();

All of the dirty work is handled by the libraries in the API and you do not need Office installed on the machine generating the documents! It is really simple and effective, which is a HUGE credit to the library, and the authors porting it to help .Net developers. There is a lot more available in these libraries, which is worth looking into!

Similar to my other “Soup to Nuts” type articles, I’ve created a C# and a VB.Net project that contains everything you need to export a GridView to Excel for viewing. I’ve done a little header formatting in the example, as well as include an option to exclude columns from being exported (as in the case when you have a GridView with action links in one of the columns. I’ve also included a sample on how to export the GridView to a file and how to export the GridView to a file and prompt the user to download/open it. Many thanks to NPOI for making my life a lot easier, and hopefully this will help you to!

Visual Studio 2010 Solutions
S2NGridViewExcelCS (C#)
S2NGridViewExcelVB (VB)

Visual Studio 2008 Solutions
S2NGridViewExcelCS (C#)
S2NGridViewExcelVB (VB)

Note: You’ll need 7-Zip to extract these files:

Centering Tables with HTML/CSS

What?! You’re not using CSS layouts for a table-less presentation. How awful!

Don’t cry foul just yet.

There ARE still some places out there on the web (notably internal LOB apps that have predefined grids like objects) that are using tables to display their content. As a matter of fact, there are still some places where tables work better, especially when you’re doing just that, displaying tabluar data.

With the older versions of web browsers and HTML, you could simply add an align=”center” snippet to your table, or even wrap the table in a div or paragraph tag that has it’s text alignment centered and be done with it.

In today’s browsers, you get mixed results, with most of them leaving the table aligned to the left side of the screen The reason this worked though, was that the browsers weren’t adhering as strictly to HTML guidelines and giving the box element of the table a pass and went ahead and centered the table for you. As HTML5 is finalized and browsers stick closer to CSS3 guidelines, I’m sure none of them will use this old method.

Fortunately though, the solution to this is simple, almost too simple. It surprised me how long it took me to figure this one out. To my credit (or excuse 8^D) I was still getting the hang of CSS and learning how the box model does things. Alas, enough babble and on to the code.

To center your table (or GridView objects if you’re using ASP.Net), simply create for yourself two classes:

.align-center
{
   text-align: center;
}

.CenterTable
{
   margin-left: auto;
   margin-right: auto;
}

The first class is self explanatory. It is really just an alias to the standard text alignment. However, I like to use this class because it is named a little more friendly for me and allows me to use multiple classes when necessary on an element without having to mix style and class tags within.

The second class was a bit trickier. What this class does is allows the browser to calculate the left and right margins for the table, which in turn makes sure it centers itself up within whatever containing box it is in, or the page itself. I’ll admit that I’m no CSS guru, so that explanation still seems a bit magical to me.

Regardless, when you’re ready to roll, all you have to do is this:

<div class="align-center">

   <table class="CenterTable">
      <tr>
         <td>Woot!</td>
         <td>Centerized!!!</td>
      </tr>
   </table>

</div>

Or similarly:

<asp:Panel Id="pnlClaims" runat="server" CssClass="align-center">
   <asp:GridView ID="gvClaims" runat="server"
                 AllowPaging="True"
                 AllowSorting="True"
                 AutoGenerateColumns="True"
                 CssClass="CenterTable"
                 Width="500px">
   </asp:GridView>
</asp:Panel>

That’s all there is to it. Simple, handy, reusable.

Hope this helps!

Soup to Nuts: Sorting/Paging/Managing a GridView

As much as I love the latest and greatest stuff coming out of the .Net camp (still catching up on my MVC2 video tutorials) I work in a pretty standard “Line of Business” (LOB) environment. We use ASP.Net Webforms and I doubt things will change anytime soon.

One of the most used items when developing our applications is the GridView. Its a great server control. There are a lot of features built into it that make for a great control to manage data with. You can sort, page, update, delete, and even perform custom commands within it.

That said, I’ve never found a really nice comprehensive article/source to cover all of these features available, though the MSDN documentation helped a bit. Since I had just finished a project in which I was doing all of these features with the GridView, I thought now would be the perfect time to put together a “Soup to Nuts” solution that had all of these features. It would be packed up into a solution that you could actually run and interact with, instead of just looking at snippets and imagining how they came together.

So I humbly present to you my S2N (Soup to Nuts) GridView. Simply download the appropriate file, unzip it to the location of your choice, and open up the solution file in Visual Studio. The solutions have already been compiled and tested. They have also been configured to use the built-in web server with Visual Studio, so you don’t need to worry about having IIS installed on your machine if it isn’t already there. I’ve packed the following “features” into the solution and provided a little bit of documentation within the code outlining:

  • Sorting records in the GridView.
  • Paging records in the GridView.
  • Inline Edit & Delete of records in the GridView.
  • Using the footer of the GridView to add new records (a great space saver).
  • (Bonus) Using an XML/XSD file to function as a simple database (based on my article).

To some degree there is a lot to be said about the various features of the GridView, and maybe I’ll do some individual posts about the various features found within the samples.

A couple of disclaimers to note:

The data isn’t that robustly structured. You can have multiple folks with the same name (different departments). In addition, the department should have been a separate table, but hey, this is a demo. 8^D

You’ll notice on the .aspx page that there are no databinding <%= %> type elements within the template columns. I’ve always had a preference to do my custom column data binding through the RowDataBound event. I find this a bit cleaner to manage and gives you some extra options to work with. I guess I’ll have to write up an article on that at a later date. 8^D

If you’re looking for some extra magic to do with a GridView, especially with AJAX, I highly recommend Matt Berseth’s blog. He hasn’t done any updates in about a year now, but there are a lot of great articles to read through there.

Hopefully these code samples will give you an good overview of the GridView if you’re just getting started with it. If you’re a “veteran” of the control, hopefully these code samples will make for a nice template to use when rolling out a new GridView in your application.

As always, all comments/suggestions are greatly appreciated.

Visual Studio 2010 Solutions
Visual Basic: S2NGridViewVB_2010 (170 KB)
C#: S2NGridViewCS_2010 (76KB)

Visual Studio 2008 Solutions
Visual Basic: S2NGridViewVB_2008 (168KB)
C#: S2NGridViewCS_2008 (73KB)