5 November 2014

Show delimiter Text file data to DataGridView

Hi All,

Lets see how to show the delimiter text file in DataGridView in C#.  Lot of use face the problem when we have CSV or any other delimiter text file and asked to show it as table in C# DataGridView.

As one user asked at Stackoverflow


You can have to copy paste the following code and ready to go..

using System.Data;
using System.IO;


public class Helper
{

 public static DataTable DataTableFromTextFile(string location, char delimiter=',')
 {
     DataTable result;

     string[] LineArray = File.ReadAllLines(location);

     result = FormDataTable(LineArray, delimiter);

     return result;
 }


 private static DataTable FormDataTable(string []LineArray, char delimiter)
 {
     bool IsHeaderSet = false;

     DataTable dt = new DataTable();

     AddColumnToTable(LineArray, delimiter, ref dt);

     AddRowToTable(LineArray, delimiter, ref dt);

     return dt;
 }


 private static void AddRowToTable(string []valueCollection, char delimiter, ref DataTable dt)
 {

     for (int i = 1; i < valueCollection.Length; i++)
     {
     string[] values = valueCollection[i].Split(delimiter);

     DataRow dr = dt.NewRow();

     for (int j = 0; j < values.Length; j++)
     {
         dr[j] = values[j];
     }

     dt.Rows.Add(dr);
     }
 }


 private static void AddColumnToTable(string []columnCollection, char delimiter, ref DataTable dt)
 {
     string[] columns = columnCollection[0].Split(delimiter);

     foreach (string columnName in columns)
     {
     DataColumn dc = new DataColumn(columnName, typeof(string));
     dt.Columns.Add(dc);
     }

 }

}

Thats all.. ready to use.. Now let me tell you how to bind this with DataGridView just call

// if | is delimiter char
//fname| sname| age
//deepak| sharma| 23
//Gaurav| sharma| 32
//Alok| Kumar| 33
dataGridView1.DataSource = Helper.DataTableFromTextFile("Testing.txt", '|');


//if comma , is delimiter char like - 
//fname, sname, age
//deepak, sharma, 23
//Gaurav, sharma, 32
//Alok, Kumar, 33
dataGridView1.DataSource = Helper.DataTableFromTextFile("Testing.txt");


if pipeline(|) is delimiter character else pass what else it is.  Default delimiter char is common(,) so in case of (,) no need to even pass it.

It works like charm. :)




Happy Coding.. and Sharing.. :)

17 September 2014

Convert C# DataTable to JavaScript 2D Array

Hi All,

Lets see how to send the DataTable from Code behind to JavaScript.  Some time we face the problem when we need to array the value from C# code behind to JavaScript use use script tag <%=variable_name%> Right we are also going to use the same approach. But the main point is how to convert the DataTable(or Dictionary or List of object) from C# to JavaScript.

Someone might come up with the thought to use the Repeater control.  But its really typical,  What about if I say you can get the C# DataTable  as 2D array in JavaScript with no extra efforts??

:) Cool...

you just need to pass your DataTable in this method and it will create the Json Serialized array to be used in JavaScript. :)

   public partial class RepeaterControlTesting : System.Web.UI.Page
   {
      public string dataTable;        
      protected void Page_Load(object sender, EventArgs e)
      {
         if (!IsPostBack)
         {
            dataTable = ConvertDataTabletoString(getDT());                
         }
      }
      public string ConvertDataTabletoString(DataTable dt)
      {            
          JavaScriptSerializer serializer = new JavaScriptSerializer();
                   
          List<List<object>> rows = new List<List<object>>();
          List<object> row;
          foreach (DataRow dr in dt.Rows)
          {
             row = new List<object>();
             foreach (DataColumn col in dt.Columns)
             {
                row.Add(dr[col]);
             }
             rows.Add(row);
          }

          return serializer.Serialize(rows);
      }
      public DataTable getDT()
      {
          /// or get the DataTable from Database.. 
          DataTable dt = new DataTable();
          dt.Columns.Add("Col_int", typeof (int));
          dt.Columns.Add("Col_string", typeof(string));
          dt.Columns.Add("Col_bool", typeof(bool));
          dt.Columns.Add("Col_4th", typeof(string));
          dt.Columns.Add("Col_float", typeof(float));

          DataRow dr;
          for (int i = 1; i <= 5; i++)
          {
              dr = dt.NewRow();
              dr[0] = i;
              dr[1] = i + "  Col_string";
              dr[2] = (i%2 == 0);
              dr[3] = i + " Col_4th";
              dr[4] = (float)i;

              dt.Rows.Add(dr);
          }

          return dt;
      }

  }

Thats it.. now just goto you aspx file and access the "dataTable" in your JavaScript code..

<body>
    <div id="main">
                
    </div>
        
    <script>        
        var dataTable = <%= this.dataTable %>;
        for (var i = 0; i < dataTable.length; i++) {
            $("#main").append("| "+dataTable[i][0] + " | ");
            $("#main").append(dataTable[i][1] + " | ");
            $("#main").append(dataTable[i][2] + " | ");
            $("#main").append(dataTable[i][3] + " | ");
            $("#main").append(dataTable[i][4] + " |<br/><br/>");
        }
    </script>
</body>



Good to go.. :) Happy Code sharing.. :)

2 September 2014

SignalR - Real Time Communication

Hi All,

Today lets talk about "SignalR", I hope You might have heard about it.  But How to use it you might face some problem.
SignalR is used for real time communication, eg like - social networking site for notification, in your mail inbox for new mail arriving, real time chat application, group chatting forums and other.  Real time communication make sense and we know what does it mean.

When we try to implement real time relationship, the first way came in our mind it polling.. Long-polling or short-polling.. But what about if I say we have one more efficient method then polling?  Oh you got it? is that Web-Socket??  Yes it is.. but if you are going to use Web-Socket or any other HTML5 elements you have to make it sure you are going to support few old browsers as well which doesn't support HTML5 elements.

Now you  might think about long-polling with Web socket?  web-socket for new browser and polling for old browser? Right?

Yes that the way to support the old and new browser. But you have to code for polling and web-socket, then check the browser support, then call the supported coding snippet.  But I am saying no need to code for all SignalR here to do all this.  SignalR is enough intelligent to figure out what to use and how to use.  No need to code for polling and web-socket.

SignalR check the client and Server both, if both support the Web-Socket it goes for web-socket else efficient polling.  The best part is you no need to worry about it and coding part, it takes care for that. :)  Lets see for example and dependencies..


  • JQuery > 1.6 
  • SignalR  JS file
  • SignalR dll
  • Owin dll
  • Newtonsoft.Json dll


but again no worry, follow the below steps one by one - (Download Sample from here)

  • Open your Visual Studio and Create new blank Web Project.
  • Go to TOOLS >  NuGet Package Manager  >  Package Manager Console.  Type the following command on console and hit the  <Enter>, it will process and install and add the reference to your project..
    install-package Microsoft.AspNet.SignalR
  • install this package, it will automatically download all the dependencies and required dll all jquery files.
  • Right click project and add one class called as "Startup.cs"(name should be same) and paste the following code.
  • using Microsoft.Owin;
    using Owin;
    
    [assembly: OwinStartup(typeof(SignalR_For_Upload.Startup))]
    namespace SignalR_For_Upload
    {    
      public class Startup
      {
        public void Configuration(IAppBuilder app)
        {
           app.MapSignalR();
        }
      }
    }
    
    
  • Now create another class file and named it as "MyHub.cs", and paste the below code
  • using Microsoft.AspNet.SignalR;
    using Microsoft.AspNet.SignalR.Hubs;
    
    namespace SignalR_For_Upload
    {
      [HubName("newNameOfHub")]
      public class MyHub : Hub
      {
        public void SendMsg(string message)
        {
          Clients.All.ReceiveMsg(message);
        }
      }
    }
    
    
  • So the above is the Hub which keeps track of all the client and send the message to them using the statement stated above. 
  • Clients.All.ReceiveMsg(message);
    here 'Client.All' mean all the clients while 'ReceiveMsg(message)' is the dynamic expression which can be considered as event name for client 
    
  • Thats all now no more coding .. :) just need to bind up this event from client using javascript snippet. let have a look at that part as well.
  • Create your "Default.aspx" page and replace the "body" section with the following code(You can take the plain html page as well :) no worries).
  • <body>
      <input type="text" id="msg" value=" " />
      <input type="button" id="send" value="send" />
      <ul id="message">
      </ul>
        
      <script src="Scripts/jquery-1.6.4.min.js"></script>
      <script src="Scripts/jquery.signalR-2.1.1.min.js"></script>    
      <script src='<%: ResolveClientUrl("~/signalr/hubs") %>'></script>
      <script>        
        $(function () {
            
           var con = $.hubConnection();
           var hub = con.createHubProxy('newNameOfHub');
            
           hub.on('ReceiveMsg', function (message) {
              $('#message').append('<li>' + message + '</li>');
           });
    
           con.start().done(function () {
              $('#send').click(function () {
                 hub.invoke('sendMsg', $('#msg').val());                    
              });
           });
    
        });
      </script>
    </body>
    
  • So thats it.. just save the page. and run this in two browser and check they are communication in real time.  :)  Download Sample


Happy Code Sharing.. :)

13 June 2014

Auto Complete TextBox in Window Form C#

Hi All,

Let see how to create the AutoComplete TextBox in window form.
You might be aware of Auto Complete in web page using the Ajax and JQuery plugins or using the asp.net ajax toolkit.

But when it comes to the Auto Complete TextBox in Window Form some people find it difficult.

I am gonna demonstrate you Auto Complete Textbox for months Jan - Dec.

Download Sample
  • Open Visual Studio and create a Window Form application. 
  • It will add a blank default Window Form for you.
  • Drag a label name it Months and a Input TexBox for Auto Complete Months.

  • Double Click form to open Form_Load event. and create AutoCompleteStringCollection class object.
  • Add you indented string item in object in this case months name string array.
        private void Form1_Load(object sender, EventArgs e)
        {            
            // Create the list to use as the custom source.  
            var source = new AutoCompleteStringCollection();            
            source.AddRange(new string[]
                    {
                        "January",
                        "February",
                        "March",
                        "April",
                        "May",
                        "June",
                        "July",
                        "August",
                        "September",
                        "October",
                        "November",
                        "December"
                    });
            
            // attched it with the created text box.
            textBox1.AutoCompleteCustomSource = source;
            textBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
            textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
        }

  • Bind the AutoCompleteStringCollection with textBox1.

and you are done.  Now when you run the form and just type only one character "j" it will show the months starting from "j".

Happy knowledge sharing.. ☺

26 March 2014

Parent Div height zero(0) even child div has content

Hi,

Let see what happened when we float the child div to Left or Right. Parent Div shows the height as 0.

<html>
  <head>
    <style>
      #parent
      {
        width:100%;
        height:auto;
      }
      #child
      {
        float:right;
        width:25%;
        height:auto;
        border:1px solid black;
        margin:10px;
      }
    </style>
  </head>
  <body>
    <div id="parent">
      <div id="child">
        this is the content inside the child
      </div>
    </div>
  </body>
</html>

It shows the result as -


Notice child div has content so it has the height but if child div has the height why parent div showing height as zero(0)??

Its because of you set the
float:right; 
on child div which make it position:absolute and thats why parent div height is zero.  To correct is you just need to set the overflow:hidden on parent div.

modified the css part as below -
      #parent
      {
        width:100%;
        height:auto;
        overflow:hidden;
      }
And you are good to go you will get the correct result as -

Happy Blogging and Sharing.. ☺☻