Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Thursday, January 15, 2015

Using jQuery Datatables on an ASP .NET GridView control

Lately, I've been using jQuery DataTables within several custom SharePoint apps that I've created; however, I've recently resurrected an ASP .NET Web Forms application that I was working on many moons ago and wanted to leverage jQuery DataTables on a GridView control that I'm using in this application.

What I discovered is that the crux of the matter when attempting to layer jQuery DataTables over a GridView control is that you need to format the HTML of the GridView so that it's recognizable by the DataTables code.  Essentially, your GridView needs to be formatted like so in order for it to be recognized:

<table>      <thead>           <tr>                <th></th>           </tr>      </thead>      <tbody>           <tr>                <td></td>           </tr>      </tbody> </table>

Here is what you can do at the very minimum to make this happen:

ASPX Page:

<script  type="text/javascript" language="javascript" src="Scripts/jquery-1.10.2.js"></script> <script type="text/javascript" language="javascript" src="Scripts/jquery.datatables.min.js"></script> <link type="text/css" href="Content/jquery.dataTables.min.css" rel="stylesheet" /> <div class="row">      <div class="col-md-4">               <asp:GridView ID="GridView1" runat="server" CssClass="gvdatatable" AutoGenerateColumns="true" OnPreRender="GridView1_PreRender">           </asp:GridView>      </div> </div> <script type="text/javascript">      $(document).ready(function () {            $('.gvdatatable').dataTable({});      }); </script>


ASPX Page Code-Behind:

protected void Page_Load(object sender, EventArgs e)
{
}

protected void GridView1_PreRender(object sender, EventArgs e)
{
     GridView1.DataSource = GetData();  //GetData is your method that you will use to obtain the data you're populating the GridView with

     GridView1.DataBind();

     if (GridView1.Rows.Count > 0)
     {
           //Replace the <td> with <th> and adds the scope attribute
           GridView1.UseAccessibleHeader = true;

          //Adds the <thead> and <tbody> elements required for DataTables to work
          GridView1.HeaderRow.TableSection = TableRowSection.TableHeader;

           //Adds the <tfoot> element required for DataTables to work
           GridView1.FooterRow.TableSection = TableRowSection.TableFooter;
      }
}

This code has been simplified from my original work, but I wanted to provide you with the bare bones minimum code that's needed so that you can get an idea of how to bolt this onto your existing project.  Hope this helps!

Wednesday, August 20, 2014

Parsing a CSV file in C#

Every so often, I seem to run into a situation in which I need to parse a CSV file in order to read data into a system that I'm working with.  Rather than re-invent the wheel by writing my own parser, I tend to leverage the existing Microsoft.VisualBasic.TextFieldParser to do the work (yes, even though I'm using C#).  Here is some sample C# code that demonstrates how this can be used:


using Microsoft.VisualBasic;
using Microsoft.VisualBasic.FileIO;

...

TextFieldParser parser = new TextFieldParser(@"pathToCSVFile");
parser.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited;
parser.SetDelimiters(",");
while (!parser.EndOfData)
{
     string[] cols = parser.ReadFields();
     foreach (string col in cols)
     {
          Do something with the info in each field...
     }
}

To make a long story short, this existing Microsoft object will make your life a heck of a lot easier since it tends to handle most scenarios that would require special coding (i.e. properly handling quotes).  

Friday, August 16, 2013

Convert web addresses contained in a string to hyperlinks using a regular expression

In the event you ever need to convert web addresses contained within a string to hyperlinks, I stumbled across some code on StackOverflow that will allow you to do this via a regular expression.  The code for this solution is presented as follows:


private string ConvertUrlsToLinks(string msg) 
{
    string regex = @"((www\.|(http|https|ftp|news|file)+\:\/\/)[_.a-z0-9-]+\.[a-z0-9\/_:@=.+?,##%&~-]*[^.|\'|\# |!|\(|?|,| |>|<|;|\)])";
    Regex r = new Regex(regex, RegexOptions.IgnoreCase);
    return r.Replace(msg, "$1").Replace("href=\"www", "href=\"http://www");
}

Special thanks goes to a user by the name of "Rob" on StackOverflow for providing this solution to the problem!

Tuesday, February 19, 2013

Programmatically obtain a list of files contained in a directory

If you ever need to programmatically obtain information about files contained within a given directory/folder, I've provided some sample code from a Windows Form Application I created that will provide you with that capability.  In this particular instance, my Windows App allows the user to select the directory he/she wishes to review and then populates a Grid View control with information about the files contained in the directory (i.e. in this simple example, the name of the file and the date the file was last modified):

using System.Windows.Forms;
using System.Data;
using System.IO;

public partial class Form1 : Form
{
        private FolderBrowserDialog m_fbd;

        ...

        /// <summary>
        /// When the button is clicked, the user will be prompted to select the input file to open via the OpenFileDialog
        /// control.  Once the user has selected the input file, the information in the file will be read, parsed, and then
        /// displayed in the grid view control
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnReviewFiles_Click(object sender, EventArgs e)
        {
            if (m_fbd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                DataTable dt = new DataTable();
                dt.Columns.Add("FileName");
                dt.Columns.Add("LastModifiedDate");

                DirectoryInfo dir = new DirectoryInfo(m_fbd.SelectedPath);
                foreach (FileInfo file in dir.GetFiles("*.*"))
                {
                    DataRow row = dt.NewRow();
                    row["FileName"] = file.Name;
                    row["LastModifiedDate"] = file.LastWriteTime.ToString();
                    dt.Rows.Add(row);
                }
                dataGridView1.DataSource = dt;
            }
        }

If you would only like to display information about certain types of files, you can modify the parameter of the GetFiles method call appropriately.  In the following example, the code will only display information about  .pdf files contained in the selected directory:

foreach (FileInfo file in dir.GetFiles("*.pdf"))

Yes, I know...this example provides too much code to demonstrate how easy it is to programmatically obtain info about files in a given directory, but I thought it would be fun to add the additional code that could turn this into a nice utility if needed...

Friday, June 22, 2012

Remove special characters from a string using Regular Expression

If you're looking for an efficient way to remove special characters from a string, here is some sample code that utilizes a Regular Expression to do so:

using System.Text.RegularExpressions;
...
string inputString = "Sherman's Test #123";
string cleanOutputString = Regex.Replace(inputString,  @"[^A-Za-z0-9-_]", "");

This code sample will remove all characters except for alpha-numeric characters and "_".  If you would like to keep the empty characters/blank spaces, use this line instead:
string cleanOutputString = Regex.Replace(inputString,  @"[^A-Za-z0-9-_ ]", "");

Monday, December 19, 2011

Remove all leading and lagging empty spaces from items in an array

I was looking for a way to efficiently remove all leading and lagging empty spaces from items in an array in as few lines of code as possible.  In this particular instance, the goal was to read items into an array from the web.config file and then use the Trim() method to remove all leading and lagging empty spaces from each item.  Here is the code that will do this activity in just two lines for a particular, comma-delimited AppSetting node called ChargeCodesToUse in my web.config file:

string[] chargeCodesToUse = ConfigurationManager.AppSettings["ChargeCodesToUse"].ToString().Split(',');
Array.ForEach(chargeCodesToUse, chargeCodes => chargeCodesToUse[Array.IndexOf(chargeCodesToUse, chargeCodes)] = chargeCodes.Trim());