jump to navigation

Create a simple data-centric WPF application March 28, 2009

Posted by fofo in VB 9.0, Visual Studio 2008, WPF, XAML.
Tags: , , ,
trackback

I have been asked from some people to write a simple post regarding the younger and more flashy brother of  window forms. WPF is about 1 years old now and gaining ground on developers for building next generation window applications. I urge people who are new to WPF to familiarise themselves a little bit with WPF by clicking here .

In this post I am going to do just that through a very practical hands-on example. I am going to use Visual Studio and VB 2008 to build a simple data entry form.

I am going to use the Northwind database as our data store for this example.

Click here to download the installation scripts. Fire SQL Server 2005/2008 Express Edition or SQL Server Standand edition 2005/2008 and run the scripts. All the tables and their related data is now available for us to use.

1) Launch Visual Studio 2008 professional or express edition

2) Create a new project by choosing from the available templates WPF application (choose VB as your language of development)

3) Name your application myfirstWPFapp.

4) Click the Data from the menu and then click Show Data Sources.Click on the Add New Data Source link.

5) Select Database from the Dialog window and click Next .

6) Create a new connection string by clicking the New Connection. In the new window that appears choose the SQL Server name to connect to. This is of course the server that you installed the Northwind database. In my case it is FOFO-PC\SQLEXPRESS and then select the database from the dropdown list (Northwind of course). Test the connection and click OK to close the window.

7) CLick Next on the data source configuration wizard and save the connection string as NorthwindConnectionString. Click Next.

8) In the next step of the wizard from all the database objects expand the table node and select Customers. Name the dataset CustomersDataset. Click Finish.

9) In the Window1.xaml just drag and drop 4 button(on the right hand corner) controls from the Toolbox on your Wpf form. We want to add, delete,save and cancel(cancel the data that we are currently inserting) data from our Customers table. Name the buttons accordingly by changing their Name property for each one of them. I named them for example btnSave,btnCancel, e.t.c.Give them an appropriate label by changing  the Content property for each one of them.Change from the properties window some properties e.g background,foreground colors. Align the buttons and make them the same width. This is a good practice.These changes will be saved in the XAML code that you can see in the lower half of the window. We will not focus too much on the design issues in this post.

10) Drag and drop 7 label controls on the WPF form. Name them e.g lblCustomerID,lblCompanyname lblName,lblCity,lblCountry,lblRegion,lblPhone. Give them an appropriate text by changing  the Content property for each one of them.Change from the properties window some properties e.g background,foreground colors. Align them and make them the same width by setting the width property for each one of them to “100”.

11) Drag and drop 5 textboxes on the Wpf form.Name them e.g txtCustomerID, txtCompanyName,txtName,txtCity,txtCountry,txtRegion,txtPhone. Change from the properties window some properties e.g background,foreground colors. Align them and make them the same width by setting the width property for each one of them. Align the label controls and the textbox controls using the visual alignment controls. Resize the formif you want.

12) We have not finished yet. We must provide some sort of navigation controls to our application. In WPF applications we do not have ready controls(navigators) like we did with normal window forms. Drag and drop 4 button(on the left hand corner) controls from the Toolbox on your Wpf form. We want to allow users to navigate to the first,last,previous and next record from our Customers table. Name the buttons accordingly by changing their Name property for each one of them. I named them for example btnfirst,btnlast, e.t.c.Give them an appropriate label by changing  the Content property for each one of them.Change from the properties window some properties e.g background,foreground colors if you want. Align the buttons and make them the same width.If you have followed along every step you must have something similar with this picture below

wpf-new-1

13) That seemed like a lot of work… Ok, so now we are ready to finally do our databinding tasks. We obviously need to populate the textbox controls with data from our Customer database table through our CustomersDataSet object and the Customers Data Table object.If you have done databinding using window forms , you may think that we simply drag and drop the fields from the Data Sources window on the wpf form. We can not do that. But we can databind the textboxes to their respective values from the database from XAML code. We do that by telling each textbox Text property that is bound to the relevant field in the table. In the XAML pane we locate the first textbox, and we bind it to the CustomerID field using this code(i just typed the code in brown color):

<TextBox Grid.Column=”1″ Grid.Row=”1″ Height=”23″ Margin=”61,13,103,0″ Name=”txtCustomerID” VerticalAlignment=”Top” Text=”{Binding Path=CustomerID}” />

You do that for the remaining 6 textbox controls.

14) Now we need to load the data in our form. We must write some code in our code behind file in the appropriate event. This is the Window_Loaded event handler routine. We must create some variables for our dataset,tableadapter and tableadaptermanager. You can do this by writing something like that

Dim customerdataset As New CustomersDataSet

Dim customeradapter As New CustomersDataSetTableAdapters.CustomersTableAdapter

Dim customermanager As New CustomersDataSetTableAdapters.TableAdapterManager

Now inside the event handling routine you have

Private Sub myfirstWPFAPP_Loaded(ByVal sender As Object, ByVal e As    System.Windows.RoutedEventArgs) Handles Me.Loaded

Me.customeradapter.Fill(Me.customerdataset.Customers)

Me.DataContext = Me.customerdataset.Customers

End Sub

15) If you hit F5 and run your application you will see the first row(only the fields we specified, not all of them) of the Customers Table loaded into the 7 textboxes. That is great!!! But we do not need just the data for one record, we need all the records. For this we need to write some code in our navigation controls. In order to do that we need an object to navigate the data collection. This object is the CollectionView object.

We create a variable of that data type e.g

Dim myview As CollectionView

and inside the form Loaded Event(myfirstWPFAPP_Loaded)we type the following line to give a value to our object

Me.myview = CollectionViewSource.GetDefaultView(Me.customerdataset.Customers)

16) Double Click the button that you named “First”. An event handling routine is created. Add this line of code

Me.myview.MoveCurrentToFirst()

So the full code is:

Private Sub btnfirst_Click(ByVal sender As System.Object, ByVal e As  System.Windows.RoutedEventArgs) Handles btnfirst.Click

Me.myview.MoveCurrentToFirst()

End Sub

17) Double Click the button that you named “Previous”. An event handling routine is created. Add these three lines of code inside it. In this case we check with a very simple If statenement if we are on the first record. If not we can go to the previous one.

If Me.myview.CurrentPosition > 0 Then

Me.myview.MoveCurrentToPrevious()

End If

18) Double Click the button that you named “Next”. An event handling routine is created. Add these three lines of code inside it. Here we check if we are in the last row of our table. If not , we move to the next record.

If Me.myview.CurrentPosition < Me.myview.Count – 1 Then

Me.myview.MoveCurrentToNext()

End If

19) Double Click the button that you named “Last”. An event handling routine is created. Add this line of code inside it.

Me.myview.MoveCurrentToLast()

20) Run your application by hitting F5. Make sure that the navigation buttons operate as desired.

21) Yes it is now time to write some more code so our ,cancel,save,delete,add buttons to be operational.Double Click on the “Delete” button on your form. An event handling routine is created. Add these 4 lines of code inside it.

If Me.myview.CurrentPosition > -1 Then
Dim row = CType(Me.myview.CurrentItem, System.Data.DataRowView).Row
row.Delete()

End If

We check to see that we are in a record and that our table is not empty. Then we must get the row that is currently in view and then we simply delete it. I want to highlight something here. This Customers table is related via a foreign key constraint to the Orders table which is another table of the Northwind database. If you go to delete one record from the Customers table that has placed an order, then you will receive an error. In order to test the “Delete” button just add a brand new customer using the “Add” button first.

22) Double Click on the “Add” button on your form. An event handling routine is created. Add these 3 lines of code inside it.

Dim row = Me.customerdataset.Customers.NewCustomersRow

‘ because these fields do not allow nulls we specify some values

row.CustomerID = “[mid]”
row.CompanyName = “[my company name]”

Me.customerdataset.Customers.AddCustomersRow(row)

Me.myview.MoveCurrentToLast()

23) Double Click on the “Cancel” button on your form. An event handling routine is created. Add this line of code inside it.

Me.customerdataset.RejectChanges()

24) Double Click on the “Save” button on your form. An event handling routine is created. Add these 7 lines of code inside it.

Try
If Me.customerdataset.HasChanges Then

Me.customeradapter.Update(Me.customerdataset)

End If

Catch ex As Exception
MsgBox(ex.Message)

End Try

25)  Run your application. Add a new customer by clicking the “Add” Button and filling in the data and click the “Save” button. A new customer is in the database. Then click the “Delete” Button while the newly created customer row is active. Click the “Save’ button again.The customer is deleted. Check these changes in your actual database.

Hope it helps. If you need the source code email me at nkantzelis@q-training.gr

Happy browsing!!!!

Add to FacebookAdd to NewsvineAdd to DiggAdd to Del.icio.usAdd to StumbleuponAdd to RedditAdd to BlinklistAdd to Ma.gnoliaAdd to TechnoratiAdd to Furl

Advertisements

Comments»

1. Mohammad Jabed Akther - September 7, 2009

Excellent code..It’s really help a lot… Thanks..

2. Developer - January 17, 2010

That is good, simple and ready to be used.
Thanks for providing the code with nice explanation.
keep goin writing new post like this.

3. Remi - January 29, 2010

verry good,
I used it with express 2010 on window7 with an access mdb and altered the code
where i needed to
Thanks

Vikram Rawal - July 1, 2010

It’s a Glamour and it’s very useful when making Project
Thanks!!!!!

4. VikramRawal - July 1, 2010

It’s a Glamour

5. Kanak - January 2, 2011

I tried this code. When I click the save button, it updates itself. But when I restart visual studio, I don’t see my new updated entries. Besides, the real table (in server explorer) doesn’t update at all. So how to solve this?

6. jon - January 31, 2011

cheers for the info. am hoping it will help got a excel vb databse that needs to upsized and changed to SQL server.the forms are really good and want to keep them just struggling linkg the data from excel form to sql. this will go along way to assist thanks
hope l can return the favour some day oh am elctronics design engineer not software development but l said would do it so there we go next time keep my mouth shut and get it to one of you guys!!
jon

7. ahmed - June 1, 2012

Thank You so Much May Allah keep Guiding you


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: