Translating a windows form to WPF

ddanbe 1 Tallied Votes 541 Views Share

After reading this excellent code snippet by djjeavons, and just trying to learn WPF, I decided: "Well, let's translate that to WPF!". It was a bit harder than I thought, but a great learning experience! Her's how my screen in action looks:
WPFscreen.png
Things that changed compared to the Forms version:
--- OpenFileDialog works a bit different.
--- WPF has no DataGridView but another beast called DataGrid
--- Exiting an application has also changed.
The communication with Excel still worked seamlessly.
I managed to overcome the difficulties and learned alot in doing so.
Hope you enjoy to find out all the code differences. :)
My code is included, the XAML as well as the code behind.
Have fun!

EDIT: The colors on my window are not meant to "beautify" the whole thing, but helped very good to keep track of all my WPF panels.

Santanu.Das commented: Nice snippet +5
cs file
-------

using System;
using System.Collections.Generic;
using System.Data.OleDb;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Win32;
using System.Data;

namespace ExcelCookbookReader
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void openFileButton_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openDialog = new OpenFileDialog();
            openDialog.Filter = "Excel files(*.xlsm )|*.xlsm|(*.xlsx )|*.xlsx";
            if (openDialog.ShowDialog() == true)
            {
                excelFileTextBox.Text = openDialog.FileName;
                //Get all worksheet names from the Excel file selected using GetSchema of an OleDbConnection
                string sourceConnectionString = String.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 12.0 Xml;HDR=YES'", excelFileTextBox.Text);
                OleDbConnection connection = new OleDbConnection(sourceConnectionString);
                connection.Open();
                DataTable tables = connection.GetSchema("Tables", new String[] { null, null, null, "TABLE" });
                connection.Dispose();
                //Add each table name to the combo box
                if (tables != null && tables.Rows.Count > 0)
                {
                    worksheetsComboBox.Items.Clear();
                    foreach (DataRow row in tables.Rows)
                    {
                        worksheetsComboBox.Items.Add(row["TABLE_NAME"].ToString());
                    }
                }
            }
        }

        private void worksheetsComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //Display the data from the selected Worksheet 
            string sourceConnectionString = String.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 12.0 Xml;HDR=YES'", excelFileTextBox.Text);
                        
            OleDbDataAdapter adapter = new OleDbDataAdapter(String.Format("SELECT * FROM [{0}]", worksheetsComboBox.SelectedItem.ToString()), sourceConnectionString);

            DataSet currentSheet = new DataSet();
            adapter.Fill(currentSheet);
            adapter.Dispose();

            exceldataGrid.ItemsSource  = currentSheet.Tables[0].DefaultView;          
        }

        private void closeAppBtn_Click(object sender, RoutedEventArgs e)
        {
            Application App = Application.Current;
            App.Shutdown();
        }
    }
}

XAML
----
<Window x:Class="ExcelCookbookReader.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:ExcelCookbookReader"
        mc:Ignorable="d"
        Title="MainWindow" Height="380" Width="560">
    <StackPanel VerticalAlignment="Top">
        <WrapPanel Margin="5,5,5.4,5" Background="LightBlue" Height="35" >
            <Label Content="Excel File:" HorizontalAlignment="Left"/>
            <TextBox x:Name="excelFileTextBox" Margin="7,7,7,7" Width="411"/>
            <Button x:Name="openFileButton"  Click="openFileButton_Click" Margin="5,5,5,5" Width="35"  FontWeight="UltraBold" Content=" ... " RenderTransformOrigin="1.006,0.564"/>
        </WrapPanel>
        <WrapPanel Margin="5,5,5.4,5" Background="PaleGoldenrod" Height="35">
            <Label Content="Worksheets" HorizontalAlignment="Left"/>
            <ComboBox x:Name="worksheetsComboBox"  SelectionChanged="worksheetsComboBox_SelectionChanged" Margin="7,7,7,7" Width="446"/>
        </WrapPanel>
        <StackPanel Margin=" 10" Background="Red" Height="240" VerticalAlignment="Stretch">
            <DataGrid x:Name="exceldataGrid" Height="200" Margin="0,0,-0.4,0"/>
            <WrapPanel HorizontalAlignment="Right">
                <Button x:Name="closeAppBtn" Click="closeAppBtn_Click" Margin="7,10,20,7" Width="60" Content="Close" />
            </WrapPanel>
        </StackPanel>
        
    </StackPanel>
</Window>
Santanu.Das 125 Santanu Das

Instead of line 48 to 54 in your codes you can use databinding to show your data. DataBinding is one of the beautiful part of WPF.

ddanbe 2,724 Professional Procrastinator Featured Poster

Thanks for the tip Shark_1! :) I'll have a look. I guess as the line lines now are this is "old" style programming?
As I'm practically a total noob with WPF, I was already happy to be able to translate to it and remove all the errors underway.

JOSheaIV 119 C# Addict

WPFs also can run on DirectX if I recall right. If you remember I was working on a program to transition images, I ended up using a WPF because of its storyboard objects.

The only thing I really hate about them, they are AWFUL when it comes to memory management. There are really no equivalents of dispose. I was loading in images (which you couldn't use the standard Images under the Drawing or Forms library), and had to write this converter to go between the two types. However, it was causing a horrible memory leak, I am talking gigs within mins. Had to write a try/finally at set the resource to null and call the Garbage Collector. Pretty tacky if you ask me.

(I've also got an annoying issue of them blowing a null error I STILL can find why, even though I thought I did)

I will admit though you can make forms look a lot nicer. I think it was built on a concept that a developer and designer could work in tandom and not step on each other's toes (or something along those lines).

Have you seen any issues with memory resources? Or annoying quarks

ddanbe 2,724 Professional Procrastinator Featured Poster

No weird things yet, I just started on a small scale. To get a little more grasp on WPF.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.