Create Silverlight Gallery in easy steps part-1

Hello friends,

Most of the time we require picture gallery in our websites & especially when the website in Silverlight then expectation is very high.

Although there are various design pattern which we can use in gallery design like spider design, 3 D rotation box design, grid view design, scroll design etc. I am concentrating 3 simplest designs and try to explain them one by one.

So here are the three basic gallery designs.

  1. Scroll images thumbnail in bottom and on click or some other event show enlarge image in center of the page. For reference see below fig.

2.Show all thumbnails in grid view and when we click on individual thumbnail it enlarge. For reference see below fig

3. Show the entire images thumbnails on left side with in a grid and when click on individual thumbnail it enlarge on right side. For reference see below fig.

 

So let start with first gallery design which is scroll at the bottom and on click or mouse over see the enlarge image in center.

So here are the steps.

1)      Create a new Silverlight project

2)      Now according to our design just add two rows in the grid where first row will contain related to enlarge or big image  view while second row is related with thumbnails which scroll from right to left.

3)      In grid’s first row I have added an image control.

4)      In grid’s second row I have added a stack panel because all the images we will ad at run time in the stack panel.

5)      Now we are adding some image effects in big image view control currently we have used drop shadow effect.

6)      Now as you know we have to apply some kind of logic to move image from one position to another position for these we can use translate transformation (As you know Transformation is part of animation). Translate transformation help in movement of image from one position to another position.

7)      Once our design is fixed now we will add image dynamically from code behind. Just like as shown below code.

Dim intI As Integer

        Me.stakImages.Children.Clear()

        For intI = 1 To 8

            Dim Img As New Image

            Dim imgsource As ImageSource

            imgsource = New BitmapImage(New Uri(“images/” + intI.ToString() + “.jpg”, UriKind.Relative))

            Img.Width = 100

            Img.Height = 100

            Img.Margin = New Thickness(10)

            Img.Name = “img” + intI.ToString()

            Img.SetValue(Image.SourceProperty, imgsource)

            Dim ef As New Effects.DropShadowEffect()

            ef.ShadowDepth = 10

            Img.Effect = ef

            AddHandler Img.MouseEnter, AddressOf img_MouseEnter

            Me.stakImages.Children.Add(Img)

        Next

        Me.dbAniTransform.From = 800

        Me.dbAniTransform.To = -600

        Me.photos.Begin()

8)      Here you find that I have added image handler on Mouse Enter event you can use different event as per your choice.

9)      We have added drop shadow effect also so the image looks bit emboss.

So in this way we have finished basic image gallery. Here the major points to understand are only image translate transformation. If we understand this then we can design it easily.

You can download the code from

download code
Enjoy weekend with Silverlight.

Thanks & Best Regards,

Rajat Jaiswal

Advertisements

Spell Cheker with VS 2008 ASP.NET OR HTML Application

Dear All,

Although I tried all the times to improve myself in all stream and English communication is one of the key points.

 I know I do lot of mistake in writing most of the time spell mistake. I would like to thank Mikhail Arkhipov who provided spell checker add ins with VS 2008 which help me to reduce spell mistake in my HTML & ASP.NET application. Many thanks to Mikhail Arkhipov. You can read more about VS 2008 spell check Add Ins from below Link http://blogs.msdn.com/b/webdevtools/archive/2008/11/29/spell-checker-update-2-2-full-support-for-vs-2008-sp1-simpler-setup-and-a-few-bug-fixes.aspx

And you can download VS 2008 spell checker Add INS from below link

 http://visualstudiogallery.msdn.microsoft.com/en-us/2f3d691d-8838-4d84-ad64-44a02db37e30

Once again many thanks to Mikhail Arkhipov.

 Thanks & Esteemed Regards

 Rajat Jaiswal

Host your site with me in free

Hello friends Here are some free hosting services which I prefer to use. I would like to share this with you so that you will also create your account on this and use free services of hosting from this hosting units.

1) Web Host for Asp :-

 

 2) Brinskter :-

 

3) 7 Host:-

 

Other than this there are some other services which provide free asp.net hosting like aspspider.net. So enjoy your work with this.
Thanks &
regards
Rajat Jaiswal

How to improve AJAX page Speed with 5 easy steps

Hello friends,

Many times we face the Ajax speed problem. Our AJAX page is very slow.

So here I am with  five valuable tips checkout if it helps you some where. 

1)      EnablePartialRendering:-

 Make enable partial rendering = true in script manager

Its syntax is as shown below

“<asp:ScriptManager ID=”scm” runat=”server”  EnablePartialRendering =”true”   >”

It enable partial rendering so use does n’t have to wait a long for page.

Remember its useful only when you have multiple panel update. 

2)      Script Refrence Profiler dll:-

This is one of the most important DLL by which you can imporve your page performance.

Its simple in use you have to do just drag and drop Script refrence profiler in Div. Then run the page it will give you all refrence Scripts.

As shown below fig.

 ScriptRefrence1

 Just copy this and page in script tag of Script manager as shown below.

<asp:ScriptManager ID=”scm” runat=”server”  EnablePartialRendering =”true”   >

    <Scripts>

<asp:ScriptReference path=”../Includes/Scripts/System.Web.Extensions/1.0.61025.0/MicrosoftAjax.js”/>

</script>

</asp:scriptManager> 

3)      Script Mode=”Release”:- 

Try to make script mode always release for better performance.

You have to do following setting

<asp:ScriptManager ID=”scm” runat=”server”  ScriptMode =”Release”>

 4)      LoadScriptBeforeUI=”false”:-

This should be false for better result. When you do this then screen comes fast.

 5)      Composite Script:-

 If you are using Asp.net 3.5 with service pack 1 then there will be a nice tag which is called Composite script tag.

By the name its clear that it composite all the script its syntax is as follows.

<asp:ScriptManager ID=”scm” runat=”server”  ScriptMode =”Release”>

<CompositeScript ScriptMode =”Release”>

     <Scripts>

        <asp:ScriptReference Name=”MicrosoftAjax.js” ScriptMode=”Auto” Path=”../Includes/Scripts/System.Web.Extensions/1.0.61025.0/MicrosoftAjax.js”>

        </asp:ScriptReference>

        <asp:ScriptReference Name=”MicrosoftAjax.debug.js” ScriptMode=”Auto” Path=”../Includes/Scripts/System.Web.Extensions/1.0.61025.0/MicrosoftAjax.debug.js”>

        </asp:ScriptReference>

        </script>

</compositeScript>

 If you find any error related size then just concentrate on following link its very good to solve that kind of problem.

http://bellouti.wordpress.com/2008/09/14/combining-javascript-files-with-ajax-toolkit-library/

 So ,friends in this way we improve our AJAX Page.

I hope you like this so enjoy AJAX.

 Thanks

Rajat Jaiswal

WPF Windows Persentaion Foundation with me PART- I

Hello friends,

Today we will discuss one of the most popular technologies which are silver light.
Before going forward you have some query in your mind. As I have so we will first solve that. See following questions.
1. What is Silver light?
Answer: – Silver Light is programmable web browser plug in, that enable feature such like vector graphics, animation and audio, video play back. It provide cross browser compatibility.
Its main aim to provide RIA (Rich Internet Application).Its Consistency with WPF (Windows Presentation Foundation). XAML (extensible Application Markup Language) is base of Silver light.
Its main use to provide end user a rich web application experience
Silver light basically used for RIA (Rich Internet Application) and with help of it we can make user friendly and all browser supported web sites.

2. What is XAML?
Answer: – XAML is core of Windows Presentation foundation. Its full form is Extensible Application Markup Language it’s just like a xml language with certain fixed tags. Like canvas, rectangle, grid etc…

3) From where I can download toolkit?
Answer: – We can download silver light 3.0 toolkits from http://www.silverlight.net site which is official site.

Here I will explain basic example of silver light. We are going to make a simple add 2 integer programs. I know you all aware of this but I started this for step by step progress in silver light.
For this you have to first install 3.0.
Once you have installed silver light 3.0 you will get following projects in asp.net new project window. Just select silver light application in this.

NewProject

Once you have selected this then next screen comes up for the web site or web application selection. As shown below. I have selected web application.

SilverlightOption

After selecting web application project you will get 2 projects in your solution explorer one is for silver light in which there will be .XAML file. And another one is web application which is used to call XAML file in the compile format which is called XAP.

ProjectExplore
Now we start our actual work of making 2 digit sums in silver light application
For this we have to select mainPage.xaml.
In this XAML page we have to put all the control which is requiring like textbox, label or Text Block and button.
Suppose we have to add a TextBlock in page then see below lines

 Here x:Name is like id in our ASPX page it should be unique. Grid.Row = 0 and grid.column =0 shows position in grid.

Now similarly if you want to add a label and Textbox and button then
You have to follow below code.
<dataInput:Label x:Name=”lblResult” Grid.Row=”3″ Grid.ColumnSpan=”2″ HorizontalAlignment=”Center”></dataInput:Label>

<TextBox x:Name=”txtSecond” Width=”100″ HorizontalAlignment=”Left” Grid.Row=”1″ Grid.Column=”1″></TextBox >

< Button Name=”btnAdd” Content=”Add” Click=”btnAdd_Click” Width=”100″Grid.Row=”2″ Grid.ColumnSpan=”2″ HorizontalAlignment = “Center” >
</Button >
So the main this which you have to concentrate for alignment, colors.
In Next post we will come up with some solid project base & tool kit understanding.

till than  happy programming.

Thanks
Rajat

Understand FTP with asp.net in 5 minutes part-Ist

Hello Friends,
Today I am going to share you new thing in asp.net 2.0 which is “FTP object”. Earlier in dot net 1.1 versions there is many problem to handle “FTP”, means if you want to upload or download a file then you have to do socket programming.
Which I don’t like really but after 2.0 this problem is resolved dot net provide great solution which allow us to connect with ftp and do operation.
I will explain you with my example. So today we took how to upload a file on ftp.
For this I have design following page.

FTPUpload
On this page there is 3 text box & file upload control basically which is
txtFtp – which keep ftp url like ftp://myftp.com
txtUserName – which keep ftp username for credential
txtPassword – which keep ftp password for credential
ctrlFlup – which keep path from where we have to upload file.

There is a button which is btnUpload on page. On click of this page we are going to upload the selected file.
So in code behind our first and most important statement is import J
Just see below code
Imports System.Net
Imports System
Imports System.Net
Partial Class _Default
Inherits System.Web.UI.Page

Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpload.Click
Try
Dim ftpRes As FtpWebRequest = DirectCast(FtpWebRequest.Create(Me.txtFtp.Text & “/” & Me.ctrlflUp.FileName), FtpWebRequest)
ftpRes.Credentials = New NetworkCredential(Me.txtUserName.Text, Me.txtPassword.Text)
ftpRes.Method = System.Net.WebRequestMethods.Ftp.UploadFile
Dim b As Byte() = Me.ctrlflUp.FileBytes
Dim fstream As System.IO.Stream = ftpRes.GetRequestStream()
fstream.Write(b, 0, b.Length)
fstream.Close()
fstream.Dispose()
Dim myresponse As FtpWebResponse = DirectCast(ftpRes.GetResponse, FtpWebResponse)
Response.Write(myresponse.StatusDescription)
Catch eh As System.Net.WebException
Response.Write(eh.Message)
Catch ex As Exception
Throw ex
End Try
End Sub
End Class

Here I will explain you the ftpwebrequest is the object which interact with FTP.
So when button upload is click we first create a object of ftp web request.
Once the object is created its credential is required for which we create a new network credential and just pass username & password.
After this you will find another important statement which is Web Request method.
Basically its notify that what user want to do import file, upload file, change directory etc.
In Next step what ever the file which we want to upload just convert that in byte array.
By file upload object as shown below
Dim b as byte() = me.ctrlflUp.fileBytes()
Once it done we just create a stream to write file on ftp.
So we just create a IO stream and write file on ftp.
To get response from Ftp as you know FTP has special command and status so we use ftp web response object.
If there is proper status then we can say our file is uploaded successfully.
In next Session we are going to download file from ftp with the help of this object.
Till then enjoy programming
Enjoy ftp.

Your friend
Rajat Jaiswal

WCF Windows Communication Foundation in 5 minutes Part 1

Hello Friends,

Today I am going to discuss new topic which is WCF.

As you know today market demand is Services. Every company needed Service Oriented Architecture (SOA) and in SOA first and basic thing is communication for service so Microsoft provide a  new way of communication for services which is WCF. So let’s start with our questionnaires.

1. What is WCF?

Its full name is Windows Communication Foundation. It’s also called Indigo. Its basically introduce in Dot net 3.0.

WCF is new way of communication between client & server. Its technology by which a client & server can communicate with each other. It provides direct support for Service orientation. Its help in distributed application creation its work as separate layer for communication.

Or in other way we can say that its combination of

1) .Net Remoting

2) MSMQ

3) Web Services

4) COM +

Its basically provide Service.

The Mail dll for this is “System.ServiceModel.dll” and main Namespace Is ” System.ServiceModel”

In WCF there are 3 basic conceptual parts.

1) Services: – The Services are programs which respond to clients. They can send or receive Messages.

2) Client: – Client is that program which consume services the request for services. They either send messages or receive messages or both.

3) Intermediaries: – that’s server as bridge between client & services as shown in below fig.

 clip_image0012

2. What’s advantage?

Now as a human tendency you will think “Why?”  While we have Dot net Remotings, Web Services MSMQ, DCOM then why Microsoft introduces the “WCF” indigo.

So I will say that Microsoft Sees future. Now the era is For SOA (Service Oriented Architecture). So that’s the time demand to come with solid technology which can communicate Dot net to dot net application  + dot net to Other language Application too.

When you talking about dot net to dot net application then in that case Remoting is perfect.

But when you talking about dot net to other application Web Services is perfect. But when you talking about both the things at same time then?

At that time WCF is most perfect.

Now here if you go in deep Remoting use TCP/IP protocols for communication & web services stick with SOAP or http.

So Microsoft takes WCF in picture which is much flexible.

Other than that there are few more advantages

SOA: – Its provide Service Oriented Architecture. It provides developer to make just a simple Config base communication model.

 So just define your services and use those services according to you.

Interpretability: – WCF provide Interpretability. It integrates with other technologies also and gives great way to work with them.

Ws-* :- WCF follows Ws-* specification  which are define by Microsoft, SUN, IBM and many other big company together so that they can expose there services with common protocol.

3. Necessary component?

There are following WCF which are as below:-

1) Contract Definition: – A Service must have a service contact. It can contain multiple Service contract, Data Contract or operational contract.

2) End point Definition: – Address binding contract for binding necessary

3)  Hosting code: Some hosting code needed to create service & start services

In other word we can say service class also needed.

 

4. How it works?

To understand the WCF you have to learn ABC doesn’t laugh on it: D. Here ABC means Address Binding Contact.

 Here A- Address says where there is service or which services we have to contact.

        B- Binding says How to contact with services which ways we have to connect.

       C- Contract means what part of services which we have to access.

 clip_image002

We will study in detail in my next post with sample code.

So just wait for 2nd part of this till than

Thanks & Esteemed Regards

Rajat

Why and Why not Asp.net 3.5 MVC Projects ? Asp.net 3.5 MVC Project series – IInd

Hello Friends,

Today we just try to make a sample project so I am taking here task to make a simple friend List in that list we can add friends and view friends.

So just follow the step as I mention below and we together make it easy

Step 1:- Add A project for Asp.net MVC as shown in below fig.

mvc1

Step 2:- once you done with this you will find default folders of Views, Model and controller.

The point to remember here is all the presentation layer comes in views folder and if there is sub folder in views so there must be a controller with that particular name.

As you see there is home folder in Views so in controller folder there must be Home controller exists.

The view name or we can say our page name will be the function or procedure in controller.

Suppose there is page in views –> Product –> ProductList.aspx

So in our project there must be a product controller and in that controller there must be a sub routine for product List.

There is also a shared folder in our application which is mainly used to keep shared views like Master Page & other custom controls. 

mvc2

Step 3:- Define views in home folder

1) Index.aspx :- it will be our default page. This page having default text and pictures of you

mvc3

2) AddFriend.aspx :- It is used to add friends in our database.

mvc4

3)ViewFriends.aspx:- it is used to search friend by location.

mvc5

3)SearchFriendsByArea.aspx:- it is used to find location of friend on Google map.

mvc6

 Step 4:- Now we create a database for it. In our database there is single table which is “TblFriends” with field lngId, strFirstName, strLastName, strEmailAddress, strAddress, strCity, strCountry, strphone,strBrief intro.

 Step 5:-Now and LINQ to SQL class which is  “FriendsDb.dbml”  in Model. This is use to intract with Database.

 Step 6:- We have Home Controller now we have to add different method in according to our View, Like Index, AddFriend, viewFriends, SearchFriendByArea

Once you done with this. Now we think about how the data will save from add friend.aspx. For this we just mention another function in home Controller which is Save Friend.

Save Method have all the parameter which is on the form like, strFirstName , strLastName etc.

Once you got all the require parameter we just going for add as shown below.

 Function SaveFriend(ByVal FirstName As String, ByVal LastName As String, ByVal Mobile As String, ByVal Email As String, ByVal Address As String, ByVal city As String, ByVal country As String, ByVal BriefIntro As String) As ActionResult

        ‘Require validation…

        ‘ Basic parameter validation

        Dim blnValidate As Boolean = True

        Dim errors As New List(Of String)

        If FirstName.Trim = String.Empty Then

            errors.Add(“Your first name is required!”)

            blnValidate = False

        End If

        If LastName.Trim = String.Empty Then

            errors.Add(“Your Last  name is required!”)

        End If

        If city.Trim = String.Empty Then

            errors.Add(“your city is required!”)

        End If

        If country.Trim = String.Empty Then

            errors.Add(“Country is required!”)

        End If

        If Address.Trim = String.Empty Then

            errors.Add(“Address is required!”)

        End If

        ‘Save Data i

        If blnValidate = True Then

            Dim clsFriend As New MyFriend

            clsFriend.strFirstName = FirstName

            clsFriend.strLastName = LastName

            If Mobile.Trim <> String.Empty Then

                clsFriend.strMobile = Mobile

            Else

                clsFriend.strMobile = Nothing

            End If

            If Email.Trim <> String.Empty Then

                clsFriend.strEmail = Email

            Else

                clsFriend.strEmail = Nothing

            End If

            If country.Trim <> String.Empty Then

                clsFriend.strCountry = country

            Else

                clsFriend.strCountry = Nothing

            End If

            If city.Trim <> String.Empty Then

                clsFriend.strCity = city

            Else

                clsFriend.strCity = Nothing

            End If

            If BriefIntro.Trim <> String.Empty Then

                clsFriend.strBriefIntro = BriefIntro

            Else

                clsFriend.strBriefIntro = Nothing

            End If

            If Address.Trim <> String.Empty Then

                clsFriend.strAddress = Address

            Else

                clsFriend.strAddress = Nothing

            End If

             db.MyFriends.InsertOnSubmit(clsFriend)

            db.SubmitChanges()

             ViewData(“Title”) = “Record is Saved”

            Return RedirectToAction(“ViewFriends”)

        Else

            ViewData(“Errors”) = errors

            Return View(“AddFriend”)

        End If

     End Function ‘SaveFriend

Step 7:- for searching we will do following thing

 Function SearchFriendsByArea(ByVal Area As String, ByVal city As String, ByVal country As String)

        ‘Search Friends And return

        Dim mylist = From f In db.MyFriends Where f.strAddress Like Area Or f.strCity Like city Or f.strCountry Like country Select f Order By f.strFirstName, f.strLastName

        Return View(mylist.ToList)

    End Function ‘SearchFriendsByArea

Here the things to understand the Return view Parameter. The Return view parameter is again a data collection which we will provide to search Friend’s View.

On this page we have to consider only one thing which is as follows

Inherits System.Web.Mvc.ViewPage(Of List(Of MyFriend))

 Means we provide View Data a data list of Linq Class which is MyFriends.

Now we can use it in aspx page.

<%  For Each mfriend As MyAddressBook.MyFriend In ViewData.Model%>

            <tr>

                <td>

                    <% =mfriend.strFirstName%>

                </td>

                <td>

                    <% If mfriend.strLastName Is Nothing = False AndAlso mfriend.strLastName.Trim <> String.Empty Then%>

                    <%=mfriend.strLastName%>

                    <%Else%>

                    &nbsp;

                    <% End If%>

                </td>

                <td>

                    <% If mfriend.strAddress Is Nothing = False AndAlso mfriend.strAddress.Trim <> String.Empty Then%>

                    <%=mfriend.strAddress%>

                    <% Else%>

                    &nbsp;

                    <% End If%>

                </td>

                <td>

                    <%=mfriend.strCity%>

                </td>

                <td>

                    <%=mfriend.strCountry%>

                </td>

                <td>

                    <% If mfriend.strEmail Is Nothing = False AndAlso mfriend.strEmail.Trim <> String.Empty Then%>

                    <%=mfriend.strEmail%>

                    <%Else%>

                    &nbsp;

                    <% End If%>

                </td>

            </tr>

            <% Next%>

 So in this way we just add records and view data.

You can download source Code from http://indiandotnet.tk

Thanks

Enjoy programming 🙂

Keep doing great Job 🙂

Why and Why not Asp.net 3.5 MVC? Asp.net 3.5 MVC Project series – Ist

1. What is MVC?
Answer: On of the most popular framework or we can say pattern is Model View Controller. It’s just like three tire architecture. This bifurcate our application in three different part or we can say layer which is presentation layer, business Layer and Data Access Layer.
Here we understand theree combination Model, View, Controller One by one.
As I mentiion above its three tier architecture design so here I explain why its three tire architecture.

1) View: – View is our presentation layer. Means what ever end user see or interact with our application is just View. In simple manner we can say it’s our forms either web or windows. If we taking about asp.net application or we application views are just our html Pages which we created normally. It’s not dependent on application Logic
2) Controller: – Controller is the part which decides which view should be render when user asks for some request. Or we can say it handle end user interaction.
Suppose I have requested “home.aspx” then its goes to controller and controller will decide which view he has to show to us. It’s our middle layer which we can business logic Layer.
3) Model: – Model is combination of our Database Layer + Business layer. It’s interacted with database like save, update, delete etc and also perform business logic.

So above are simple definitions for model view controller.
Now see below fig

mvc

In The figure you find three different entities. But there are some how dependent with each other
I will explain with the example let supposes a user request for customer data form.
Then the request first goes to controller and now controller is responsible to show a view
Suppose the view name is customerView.aspx then this view will be shown to the end user. Now what is the role of model here so model will provide data to view.

mvc1

Question: – why we use this?
Re use of code this first and most important advantage of MVC architecture. It’s single for web and windows we have to just change the views.

Suppose a company wants software of inventory on both windows and web then you don’t need to write whole code 2 times instead of this you have to write 2 views while model and controller will same for both. This is first and most important benefit.

multiplatformsupportmvc
Secondly Its give proper separation between presentation layer, Business layer and Data Layer.

As This blog is mainly for Asp.net and Sql Server so I will tell you for MVC dot net provide a new project template in Asp.net 3.5 which is Asp.net MVC project.
Now you thinking what earlier for previous version so here I will tell in earlier version dot net 1.1 Microsoft provide MUIAB (Microsoft User Inter Application Block) I will provide information an example for this in my next post.

Microsoft Asp.net 3.5 MVC project Support TDD (Test Driven Development) this is another most useful feature.

MVC use core html control which we used in asp classic (3.0) like Input, button so it is much faster then our web form application.

Microsoft Asp.net 3.5 project use URL is such a way which helpful in SEO (Search Engine Optimization).

Question: – why we don’t use it?
Again it’s depend on person to person according to there requirements or there preference that whether he want to use this pattern or not. According to me (as my experience and read from other articles) there is few disadvantage of using it.
The first and most important disadvantage which I feel is limitation in controls in direct use. There are many server controls link data Grid, List control which we used in web form project can not use directly in MVC project.
Lot of work in pure HTML which is some time irritating for the programmer who earlier works on asp. Net’s web form application with server controls.

In Next article we read basic of MVC (Model View Controller). Advantage & Disadvantage. In Next Session. I come with the example how we create a simple MVC project with asp.net 3.5
Till than friends do take care your self
Enjoy dot net
Enjoy MVC

Thanks & Esteemed Regards
From one and only one your Host 🙂
Rajat Jaiswal

How to import CSV in dotnet or direct Sql Server in 5 minutes?

Hello Friends,
Many times we require a logic by which we can import a csv file in grid or database.So don’t worry its not a big issue now For this I am taking below example this example is in VB.net (windows application)
Suppose I have csv file with following values
“ADDRESSID,ACCOUNTNO,ADDRESSTYPE,CODE,NAME,COMPANYNAME,ADDR1,ADDR2,ADDR3,
ADDR4,CITY,STATE,PROVINCE,ZIPCODE,POSTALCODE,COUNTRY,PHONENO,
EXTENSION,NOTIFICATIONEMAIL”
Or we can say above is the column name in this order the csv file is arrange.
So first what we do we just read the file for this
Me.OpenFileDialog1.Multiselect = False
Me.OpenFileDialog1.ShowDialog()
Me.txtPath.Text = Me.OpenFileDialog1.FileName
Dim sReader As New StreamReader(Me.txtPath.Text)
Dim strFile As String = sReader.ReadToEnd
sReader.Close()

Now in next step what we do we create a table with column which are exist in csv file remember we have to use same order for this we will write following code
Dim tbl As New DataTable
tbl.Columns.Add(New DataColumn(“ADDRESSID”))
tbl.Columns.Add(New DataColumn(“ACOUNTNO”))
tbl.Columns.Add(New DataColumn(“ADDRESSTYPE”))
tbl.Columns.Add(New DataColumn(“CODE”))
tbl.Columns.Add(New DataColumn(“NAME”))
tbl.Columns.Add(New DataColumn(“COMPANYNAME”))
tbl.Columns.Add(New DataColumn(“ADDR1”))
tbl.Columns.Add(New DataColumn(“ADDR2”))
tbl.Columns.Add(New DataColumn(“ADDR3”))
tbl.Columns.Add(New DataColumn(“ADDR4”))
tbl.Columns.Add(New DataColumn(“CITY”))
tbl.Columns.Add(New DataColumn(“STATE”))
tbl.Columns.Add(New DataColumn(“PROVINCE”))
tbl.Columns.Add(New DataColumn(“ZIPCODE”))
tbl.Columns.Add(New DataColumn(“POSTALCODE”))
tbl.Columns.Add(New DataColumn(“COUNTRY”))
tbl.Columns.Add(New DataColumn(“PHONENO”))
tbl.Columns.Add(New DataColumn(“EXTENSION”))
tbl.Columns.Add(New DataColumn(“NOTIFICATIONEMAIL”))

One this done then what we do we read all the rows one by one and split it with comma seprated value and create row in our table.
Dim strReadLine() As String = Split(strFile, vbCrLf)
The above line just convert single line in multiline with delimiter Vbcrlf which means Line break
One this done then we have collection of individual row in same format in our variable strReadLine
Now we read each line from strReadLine and create new row in table column
For intCount As Integer = 1 To strReadLine.Length – 1
Dim strColumn() As String = strReadLine(intCount).Split(“,”)
Dim DataRow As DataRow = tbl.Rows.Add()
For intCol As Integer = 0 To strColumn.Length – 1
DataRow(intCol) = strColumn(intCol)
Next
Next
Me.dgv.DataSource = tbl

So in this way we import a csv file and bind that files value in a dataGrid.

Friends if you don’t want to use vb.net and want directly import csv file in SQL Server then SQL Server support a unique sql command which is Bulk Copy
Suppose the file we have to import directly in a table which having this column then we have to write follow lines

BULK
INSERT tblImportTest
FROM ‘c:\rajat.txt’
WITH
(
FIELDTERMINATOR = ‘,’,
ROWTERMINATOR = ‘\n’
)
GO

So I think friends the above code solve our problems in many ways hope you like article.
You can download code from http://www.indiandotnet.tk

Thanks
Enjoy codeing, Enjoy dot net 😀
Rajat