Meo's Web site
     

http://www.meo-x.net

     Home | Information | Know-how | Sections | Documents | Services | Plus |      Blog |
 

 

 

 

 

Links / Liens:

Free C# Compilers and Interpreters

 

 

C#:

Didier Meo: Interface en C#

 

 

Downloads:

a small Meo's WPF demo about Data binding with Master-Detail and MS Access dataset in a zip file enclosed MEOReferences.exe and MEOReferences.mdb
a small Meo's demo project about Databinding in ASP.Net 4.0 with C#, LinQ to SQL and SQL Server 2008, in the file MEO_Test.zip
a small Meo's Silverlight 4.0 demo project in the file MEO_SilverlightTest.zip

 

WPF Data binding C#

WPF demo part 1: Data binding with Master-Detail and MS Access dataset

by Didier MEO, IT Consultant. 11/03/2012. e-mail: didiermeo@gmail.com

Description

 Here is a small WPF demo project about data binding with Textboxes, ListBoxes, DataTemplates, DataSets for a Master-Detail Binding scenario from a MS Access database MEOReferences.mdb. This demo project sets the DataContext property of a ListBox to the DataSet object. We bind the ItemsSource property of the ListBox myListBox to the DataTable TB_Book of a DataSet as Master. We bind the ItemsSource property of the ListBox webListBox to the DataTable TB_Website of a DataSet as Detail. We use the DataTemplates BookItemTemplate and WebItemTemplate to define how the data appears. .

 Voici un tout petit projet WPF sur les liaisons de données avec des TextBoxes, ListBoxes, DataTemplates, DataSets pour un scénario Master-Detail des données provenant d‚une base de données MS Access MEOReferences.mdb. Ce projet de démonstration définit la propriété DataContext d‚un contrôle ListBox à l‚objet DataSet. Nous faisons une liaison de la propriété ItemsSource de la ListBox myListBox à la DataTable TB_Book d‚un DataSet en tant que Master. Nous faisons une liaison de la propriété ItemsSource de la ListBox webListBox à la DataTable TB_Website d‚un DataSet en tant que Detail. Nous utilisons les DataTemplates BookItemTemplate et WebItemTemplate pour définir comment les données apparaissent.

 Hier ist ein kleines Demo-Projekt ber WPF-Datenbindung mit TextBoxen, ListBoxen, DataTemplates, Datasets fr einen Master-Detail-Binding-Szenario aus einer MS Access Datenbank MEOReferences.mdb. Das Demo-Projekt setzt die DataContext-Eigenschaft einer ListBox an die DataSet-Objekt. Wir binden die ItemsSource-Eigenschaft der ListBox myListBox mit DataTable TB_Book eines DataSet als Master. Wir binden die ItemsSource-Eigenschaft der ListBox webListBox mit DataTable TB_Website eines DataSet als Detail. Wir verwenden die DataTemplates BookItemTemplate und WebItemTemplate zu definieren, wie die Daten angezeigt werden.

download WPF demo file MEOReferences.exe and database MEOReferences.mdb (zip format)

 The xaml file MeorefWindow.xaml  Le fichier xaml MeorefWindow.xaml  Die xaml-Datei MeorefWindow.xaml

<Window x:Class="MEOReferences.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Initialized="OnLoad"
        Title="MEOReferences" Height="440" Width="980">
    
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width ="*" />
            <ColumnDefinition Width ="*" />
            <ColumnDefinition Width ="*" />
            <ColumnDefinition Width ="*" />
            <ColumnDefinition Width ="*" />
        </Grid.ColumnDefinitions>
        <StackPanel Orientation="Vertical" Grid.Row="0" Grid.ColumnSpan="6" >
            <StackPanel Background="Lavender" Height="20" FlowDirection="LeftToRight" Orientation="Horizontal" >
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="70*"  />
                        <ColumnDefinition Width="200" />
                        <ColumnDefinition Width="250" />
                        <ColumnDefinition Width="200" />
                        <ColumnDefinition Width="150" />
                        <ColumnDefinition Width="60"/>
                    </Grid.ColumnDefinitions>
                    <TextBlock Grid.Column="0" Text="ID" FontWeight="Bold" Width="70" Background="Yellow"/>
                    <TextBlock Grid.Column="1" Text="Title" FontWeight="Bold" Width="200" Background="Aqua"/>
                    <TextBlock Grid.Column="2" Text="Author" FontWeight="Bold"  Width="250" Background="LightBlue" />
                    <TextBlock Grid.Column="3" Text="ISBN" FontWeight="Bold" Width="200" Background="BlueViolet" />
                    <TextBlock Grid.Column="4" Text="Editor" FontWeight="Bold" Width="150" Background="CadetBlue"/>
                    <TextBlock Grid.Column="5" Text="Year" FontWeight="Bold" Width="60" Background="Lavender" />
                </Grid>
        </StackPanel>
        <StackPanel x:Name="BookPannel" Background="Lavender" FlowDirection="LeftToRight" Orientation="Horizontal">
            <StackPanel.Resources>   
            <DataTemplate x:Key="BookItemTemplate">
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="70*"  />
                        <ColumnDefinition Width="200" />
                        <ColumnDefinition Width="250" />
                        <ColumnDefinition Width="200" />
                        <ColumnDefinition Width="150" />
                        <ColumnDefinition Width="60"/>
                    </Grid.ColumnDefinitions>
                        <TextBox x:Name="txt_ID" IsReadOnly="True" Text="{Binding Path=ID}" Grid.Column="0" FontWeight="Bold" Width="70" Background="Yellow" />
                        <TextBox IsReadOnly="True" Text="{Binding Path=Title}" Grid.Column="1" Width="200" Background="Aqua"/>
                        <TextBox IsReadOnly="True" Text="{Binding Path=Author}" Grid.Column="2" Width="250" Background="LightBlue" />
                        <TextBox IsReadOnly="True" Text="{Binding Path=ISBN}" Grid.Column="3" Width="200" Background="BlueViolet" />
                        <TextBox IsReadOnly="True" Text="{Binding Path=Editor}" Grid.Column="4" Width="150"  Background="CadetBlue"/>
                        <TextBox IsReadOnly="True" Text="{Binding Path=EYear}" Grid.Column="5" Width="60" Background="Lavender" />
                    </Grid>
                    </DataTemplate> 
            </StackPanel.Resources>
            <ListBox Name="myListBox" Height="80" ItemsSource="{Binding Path=TB_Book}" ItemTemplate ="{StaticResource BookItemTemplate}" Background="Lavender" FlowDirection="LeftToRight" Padding="0" IsSynchronizedWithCurrentItem="True" BorderThickness="0" /> 
        </StackPanel>
        </StackPanel>
        <StackPanel x:Name="InsertBookPanel" Orientation="Vertical"  Grid.Row="0" Grid.ColumnSpan="6" Background="Lavender">
            <StackPanel Orientation="Horizontal"  >
            <TextBlock Text="ID" FontWeight="Bold" Width="70" Background="Yellow"/>
            <TextBlock Text="Title" FontWeight="Bold" Width="200" Background="Aqua"/>
            <TextBlock Text="Author" FontWeight="Bold"  Width="250" Background="LightBlue" />
            <TextBlock Text="ISBN" FontWeight="Bold" Width="200" Background="BlueViolet" />
            <TextBlock Text="Editor" FontWeight="Bold" Width="150"  Background="CadetBlue"/>
                <TextBlock Text="Year" FontWeight="Bold" Width="60" Background="Lavender" />
            </StackPanel>
            <StackPanel Orientation="Horizontal"  >
                <TextBox TabIndex="0" x:Name ="txbBID" Text="{Binding ElementName=myListBox, Path=SelectedItem.ID}" Grid.Column="0" FontWeight="Bold" Width="70" Background="Yellow" />
                <TextBox TabIndex="1" x:Name ="txbTitle" Text="{Binding ElementName=myListBox, Path=SelectedItem.Title}" Grid.Column="1" Width="200" Background="Aqua"/>
                <TextBox TabIndex="2" x:Name ="txbAuthor" Text="{Binding ElementName=myListBox, Path=SelectedItem.Author}" Grid.Column="2" Width="250" Background="LightBlue" />
                <TextBox TabIndex="3" x:Name ="txbISBN" Text="{Binding ElementName=myListBox, Path=SelectedItem.ISBN}" Grid.Column="3" Width="200" Background="BlueViolet" />
                <TextBox TabIndex="4" x:Name ="txbEditor" Text="{Binding ElementName=myListBox, Path=SelectedItem.Editor}" Grid.Column="4" Width="150"  Background="CadetBlue"/>
                <TextBox TabIndex="5" x:Name ="txbEYear" Text="{Binding ElementName=myListBox, Path=SelectedItem.EYear}" Grid.Column="5" Width="60" Background="Lavender" />
            </StackPanel> 
        </StackPanel>
        <Button Grid.Row="1" Grid.Column="0" Name="btnMeoly" Click="btnMeoly_Click" Width="40" Height="30" Content="All" />
        <Button Grid.Row="1" Grid.Column="1" Name="btnSearch" Click="btnSearch_Click" Width="70" Height="30" Content="Search" />
        <Button Grid.Row="1" Grid.Column="2" Name="btnNew" Click="btnNew_Click" Width="70" Height="30" Content="New" />
        <Button Grid.Row="1" Grid.Column="3" Name="btnUpdate" Click="btnUpdate_Click" Width="70" Height="30" Content="Update" />
        <Button Grid.Row="1" Grid.Column="4" Name="btnDelete" Click="btnDelete_Click" Width="70" Height="30" Content="Delete" />
        <Button Grid.Row="1" Grid.Column="5" Name="btnSave" Click="btnSave_Click" Width="40" Height="30" Content="Save" />
        <StackPanel Grid.Row="2" Grid.ColumnSpan="6" x:Name="DetailWebPanel" Background="Lavender" FlowDirection="LeftToRight">
            <StackPanel.Resources>
                <DataTemplate x:Key="WebItemTemplate">
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="70" />
                            <ColumnDefinition Width="300" />
                            <ColumnDefinition Width="300" />
                            <ColumnDefinition Width="260" />
                        </Grid.ColumnDefinitions>
                        <TextBox IsReadOnly="True" Text="{Binding Path=ID}" Grid.Column="0" Width="70"  Background="Yellow"/>
                        <TextBox IsReadOnly="True" Text="{Binding Path=URL}" Grid.Column="1" Width="300" Background="Aqua"/>
                        <TextBox IsReadOnly="True" Text="{Binding Path=Description}" Grid.Column="2"  Width="300" Background="LightBlue" />
                        <TextBox IsReadOnly="True" Text="{Binding Path=Email}" Grid.Column="3" Width="260" Background="BlueViolet" /> 
                    </Grid>
                </DataTemplate>
            </StackPanel.Resources>
            <StackPanel Background="Lavender" Height="20" FlowDirection="LeftToRight" Orientation="Horizontal">
                <TextBlock Text="ID" FontWeight="Bold" Width="70"  Background="Yellow"/>
                <TextBlock Text="URL" FontWeight="Bold" Width="300" Background="Aqua"/>
                <TextBlock Text="Description" FontWeight="Bold"  Width="300" Background="LightBlue" />
                <TextBlock Text="E-Mail" FontWeight="Bold" Width="260" Background="BlueViolet" /> 
            </StackPanel>
            <ListBox Name="webListBox" Height="80" ItemsSource="{Binding Path=TB_Website}" ItemTemplate ="{StaticResource WebItemTemplate}" Background="Lavender" FlowDirection="LeftToRight" Padding="0" IsSynchronizedWithCurrentItem="True" BorderThickness="0" />
        </StackPanel>
        <StackPanel x:Name="insertDetailWebPanell" Orientation="Vertical"  Grid.Row="2" Grid.ColumnSpan="6"  >
            <StackPanel Orientation="Horizontal"  >
                <TextBlock Text="ID" FontWeight="Bold" Width="70"  Background="Yellow"/>
                <TextBlock Text="URL" FontWeight="Bold" Width="300" Background="Aqua"/>
                <TextBlock Text="Description" FontWeight="Bold"  Width="300" Background="LightBlue" />
                <TextBlock Text="E-Mail" FontWeight="Bold" Width="260" Background="BlueViolet" />
            </StackPanel>
            <StackPanel Orientation="Horizontal"  >
                <TextBox IsReadOnly="True" x:Name="txbWID" Text="{Binding ElementName=myListBox, Path=SelectedItem.ID}" Grid.Column="0" Width="70"  Background="Yellow"/>
                <TextBox TabIndex="6" x:Name="txbWURL" Text="{Binding ElementName=webListBox, Path=SelectedItem.URL}" Grid.Column="1" Width="300" Background="Aqua"/>
                <TextBox TabIndex="7" x:Name="txbWDescription" Text="{Binding ElementName=webListBox, Path=SelectedItem.Description}" Grid.Column="2"  Width="300" Background="LightBlue" />
                <TextBox TabIndex="8" x:Name="txbWEmail" Text="{Binding ElementName=webListBox, Path=SelectedItem.Email}" Grid.Column="3" Width="260" Background="BlueViolet" />
            </StackPanel>
        </StackPanel>
        <StatusBar Height="34" Name="statusBar1" Width="958" VerticalAlignment="Bottom"  Grid.Row="2" Grid.ColumnSpan="6">
            <StatusBar.Background>
                <LinearGradientBrush StartPoint="0,0" EndPoint="1,1">
                    <GradientStop Color="Bisque" Offset="0.0" />
                    <GradientStop Color="Beige" Offset="0.50" />
                    <GradientStop Color="Beige" Offset="0.50" />
                    <GradientStop Color="Bisque" Offset="1.0" />
                </LinearGradientBrush> 
            </StatusBar.Background>
            <StatusBarItem HorizontalAlignment="Left">
                <Image Source="MEO_Symb.ico" Width="32" Height="32"/>
            </StatusBarItem>
            <StatusBarItem>
                <TextBlock>WPF demo part 1: Data binding with Master-Detail and MS Access dataset</TextBlock>
            </StatusBarItem>
            <Separator />
            <StatusBarItem HorizontalAlignment="Right">
                <TextBlock HorizontalAlignment="Right" x:Name="StatusMsg" Background="Crimson" FontWeight="UltraBold"></TextBlock>
            </StatusBarItem>
            <Separator HorizontalAlignment="Right" />
            <StatusBarItem HorizontalAlignment="Right">
                <TextBlock> <Bold><Italic>http://www.meo-x.net</Italic></Bold>,  e-Mail:  <Bold>meo@meo-x.net</Bold> 
                    <Italic> Developed by</Italic> <Bold>(c) Didier Meo</Bold>
                </TextBlock>
            </StatusBarItem>
        </StatusBar>
    </Grid>

</Window>

         

 The C# file MeorefWindow.xaml.cs  Le fichier C# MeorefWindow.xaml.cs  Die C#-Datei MeorefWindow.xaml.cs

// WPF demo Part1: WPF data binding with controls, listboxes and a Master-Detail Binding scenario 
// from MS Access database MEOReferences.mdb between a data table TB_Book as master and data table
// TB_Website as detail.
// Author: Didier Meo, http://www.meo-x.net | e-mail: meo@meo-x.net

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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 System.Data;
using System.Data.OleDb;

namespace MEOReferences
{
    /// <summary>
    /// Interaktionslogik fr MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        int RowCounter = 0, RowMax = 0;
        string strID = string.Empty, strChoice = string.Empty; 

        OleDbConnection connOLEDB = new OleDbConnection();  
        OleDbCommand cmdInsert = new OleDbCommand(); 
        OleDbCommand cmdUpdate = new OleDbCommand();
        OleDbCommand cmdDelete = new OleDbCommand();
        string strConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + System.Environment.CurrentDirectory + "\\MEOReferences.mdb";
        List<string> listOfID = new List<string>();
        Brush disableBrush, enableBrush, bgBrush;


        public MainWindow()
        {
            InitializeComponent();
            //InsertBookPanel.Visibility = System.Windows.Visibility.Hidden;    
            insertDetailWebPanell.Visibility = System.Windows.Visibility.Hidden;
            

        }

        private void OnLoad(object sender, EventArgs e) 
        {
            
            if (connOLEDB.State == ConnectionState.Closed)
            {
                connOLEDB.ConnectionString = strConnectionString;
                connOLEDB.Open();
            }
            try
            {
                OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM TB_Book ORDER BY ID ASC;", connOLEDB);
                DataSet myDataSet;
                myDataSet = new DataSet();
                adapter.Fill(myDataSet, "TB_Book");
                RowMax = myDataSet.Tables[0].Rows.Count;

                listOfID.Clear();
                for (int n = 0; n < RowMax; n++)
                {
                    DataRow row0 = myDataSet.Tables[0].Rows[n];
                    DataColumn column0 = myDataSet.Tables[0].Columns["ID"];
                    listOfID.Add((row0[column0]).ToString());
                }

                myListBox.DataContext = myDataSet;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                connOLEDB.Close();
            } 

            this.DetailWebPanel.Visibility = System.Windows.Visibility.Hidden;
            this.btnDelete.IsEnabled = false;
            this.btnUpdate.IsEnabled = false;
            this.btnSave.IsEnabled = false;
            disableBrush = btnSave.Foreground;
            enableBrush = btnNew.Foreground;
            bgBrush = this.btnSave.Background;
            this.btnSearch.Foreground = Brushes.Brown;
            this.btnNew.Foreground = Brushes.BlueViolet;
            myListBox.Background = Brushes.Lavender;
            StatusMsg.Text = btnMeoly.Content.ToString();
            InsertBookPanel.Visibility = System.Windows.Visibility.Hidden; 
        }

        private void getDetail()
        {
            OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM TB_Website Where ID = '" + strID + "';", connOLEDB);
            DataSet myDataSet;
            myDataSet = new DataSet();
            adapter.Fill(myDataSet, "TB_Website"); 
            webListBox.DataContext = myDataSet;

            this.DetailWebPanel.Visibility = System.Windows.Visibility.Visible;
            this.insertDetailWebPanell.Visibility = System.Windows.Visibility.Hidden; 
        }

        private void btnMeoly_Click(object sender, RoutedEventArgs e)
        {
            if (connOLEDB.State == ConnectionState.Closed)
            {
                connOLEDB.ConnectionString = strConnectionString;
                connOLEDB.Open();
            }
            
            BookPannel.Visibility = System.Windows.Visibility.Visible;
            this.btnSave.Foreground = disableBrush;
            this.btnSave.Content = "Save";
            this.btnSave.IsEnabled = false;
            this.btnSave.Background = bgBrush;
            this.btnSave.FontWeight = FontWeights.Normal;
            myListBox.Background = Brushes.Lavender;
            if (RowCounter == RowMax )
            {
                this.OnLoad(sender, e);
                btnMeoly.Content = "All";
                StatusMsg.Text = btnMeoly.Content.ToString();
                RowCounter++;
                this.btnDelete.IsEnabled = false;
                this.btnUpdate.IsEnabled = false;
                this.btnUpdate.Foreground = disableBrush;
                this.btnDelete.Foreground = disableBrush; 
                this.btnSave.IsEnabled = false;
                txbWURL.Text = txbWDescription.Text = txbWEmail.Text = txbWID.Text = "";
                this.insertDetailWebPanell.Visibility = System.Windows.Visibility.Hidden; 
            }
            else if (RowCounter < RowMax )
            {
                OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM TB_Book Where ID = '" + listOfID[RowCounter] + "';", connOLEDB);
                DataSet myDataSet;
                myDataSet = new DataSet();
                adapter.Fill(myDataSet, "TB_Book");

                DataRow row0 = myDataSet.Tables[0].Rows[0];
                DataColumn column0 = myDataSet.Tables[0].Columns["ID"];
                strID = (row0[column0]).ToString();

                myListBox.DataContext = myDataSet;
                
                btnMeoly.Content = (RowCounter+1).ToString();
                StatusMsg.Text = strID;
                RowCounter++;

                this.btnDelete.IsEnabled = true;
                this.btnUpdate.IsEnabled = true;
                this.btnUpdate.Foreground = Brushes.DarkGreen;
                this.btnDelete.Foreground = Brushes.Red; 
            }
            if (RowCounter > RowMax ) RowCounter = 0;
            if (Convert.ToString(btnMeoly.Content) == "All") this.DetailWebPanel.Visibility = System.Windows.Visibility.Hidden;
            else
            {
                this.DetailWebPanel.Visibility = System.Windows.Visibility.Visible;
                getDetail();
            }
            InsertBookPanel.Visibility = System.Windows.Visibility.Hidden;

            connOLEDB.Close();
        }

        private void btnSearch_Click(object sender, RoutedEventArgs e)
        {
            strChoice = "SEARCH";
            StatusMsg.Text = "SEARCH";
            BookPannel.Visibility = System.Windows.Visibility.Hidden;
            InsertBookPanel.Visibility = System.Windows.Visibility.Visible;
            DetailWebPanel.Visibility = System.Windows.Visibility.Hidden;
            insertDetailWebPanell.Visibility = System.Windows.Visibility.Hidden;
            this.btnMeoly.Content = ">";
            //this.btnSave.Foreground = enableBrush;
            this.btnSave.Foreground = Brushes.Blue;
            this.btnSave.Background = Brushes.SandyBrown;
            this.btnSave.FontWeight = FontWeights.ExtraBold; 
            this.btnSave.IsEnabled = true;
            this.btnSave.Content = "Go !";
            this.btnUpdate.IsEnabled = false;
            this.btnUpdate.Foreground = disableBrush;
            this.btnDelete.IsEnabled = false;
            this.btnDelete.Foreground = disableBrush; 
            myListBox.Background = Brushes.Lavender;
            InsertBookPanel.Focus();
            this.txbBID.Focus();
            txbBID.Text = txbTitle.Text = txbAuthor.Text = txbISBN.Text = txbEditor.Text = txbEYear.Text = "";
        }

        private void btnNew_Click(object sender, RoutedEventArgs e)
        {
            strChoice = "NEW";
            StatusMsg.Text = "NEW";
            BookPannel.Visibility = System.Windows.Visibility.Hidden; 
            InsertBookPanel.Visibility = System.Windows.Visibility.Visible;
            DetailWebPanel.Visibility = System.Windows.Visibility.Hidden;
            insertDetailWebPanell.Visibility = System.Windows.Visibility.Visible;
            this.btnMeoly.Content = ">";
            this.btnUpdate.IsEnabled = false;
            this.btnUpdate.Foreground = disableBrush;
            this.btnSave.IsEnabled = true;
            this.btnSave.Foreground = Brushes.Black;
            this.btnSave.Background = Brushes.Violet;
            this.btnSave.FontWeight = FontWeights.ExtraBold;
            this.btnSave.Content = "Save";
            this.btnDelete.IsEnabled = false;
            this.btnDelete.Foreground = disableBrush; 
            myListBox.Background = Brushes.Lavender;
            InsertBookPanel.Focus();
            this.txbBID.Focus();
            txbBID.Text = txbTitle.Text = txbAuthor.Text = txbISBN.Text = txbEditor.Text = txbEYear.Text = "";
            txbWURL.Text = txbWDescription.Text = txbWEmail.Text = txbWID.Text = ""; 
            txbWID.Text = string.Empty; 
        }

        private void btnUpdate_Click(object sender, RoutedEventArgs e)
        {
            strChoice = "UPDATE";
            StatusMsg.Text = "UPDATE";
            BookPannel.Visibility = System.Windows.Visibility.Hidden;
            InsertBookPanel.Visibility = System.Windows.Visibility.Visible;
            DetailWebPanel.Visibility = System.Windows.Visibility.Hidden;
            insertDetailWebPanell.Visibility = System.Windows.Visibility.Visible;
            this.btnSave.IsEnabled = true;
            this.btnSave.Foreground = Brushes.Blue;
            this.btnSave.Background = Brushes.LimeGreen;
            this.btnSave.FontWeight = FontWeights.ExtraBold; 
            this.btnSave.Content = "Save";
            this.btnDelete.IsEnabled = false;
            this.btnDelete.Foreground = disableBrush; 
            InsertBookPanel.Focus();
            this.txbBID.Focus();
            myListBox.Background = Brushes.Lavender;
        }

        private void btnDelete_Click(object sender, RoutedEventArgs e)
        {
            strChoice = "DELETE";
            StatusMsg.Text = "DELETE";
            this.btnSave.IsEnabled = true;
            this.btnSave.Foreground = Brushes.Black;
            this.btnSave.Background = Brushes.Red;
            this.btnSave.FontWeight = FontWeights.ExtraBold;  
            this.btnSave.Content = "Del ?";
            myListBox.Background = Brushes.Red;
        }
        
        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            if (connOLEDB.State == ConnectionState.Closed)
            {
                connOLEDB.ConnectionString = strConnectionString;
                connOLEDB.Open();
            }
            OleDbTransaction transaction = null;
            switch (strChoice)
            {
                case "SEARCH":
                    bool blnHasAnd = false;
                    int iNr = 0; 
                    string strSEARCH = "SELECT * FROM TB_Book";
                    if (txbBID.Text.Length != 0)
                    {
                        iNr++; 
                        blnHasAnd = true;
                        if (iNr == 1)
                        {
                            strSEARCH += " WHERE ";
                            iNr++; 
                        }
                        strSEARCH += " ID LIKE '" + txbBID.Text + "%'";
                    }
                    if ((blnHasAnd) && (txbTitle.Text.Length != 0)) strSEARCH += " AND ";
                    if (txbTitle.Text.Length != 0)
                    {
                        iNr++; 
                        blnHasAnd = true;
                        if (iNr == 1)
                        {
                            strSEARCH += " WHERE ";
                            iNr++;
                        }
                        strSEARCH += " Title LIKE '" + txbTitle.Text + "%' ";
                    }
                    if ((blnHasAnd) && (txbAuthor.Text.Length != 0)) strSEARCH += " AND ";
                    if (txbAuthor.Text.Length != 0)
                    {
                        iNr++; 
                        blnHasAnd = true;
                        if (iNr == 1)
                        {
                            strSEARCH += " WHERE ";
                            iNr++;
                        }
                        strSEARCH += " Author LIKE '" + txbAuthor.Text + "%' ";
                    }
                    if ((blnHasAnd) && (txbISBN.Text.Length != 0)) strSEARCH += " AND ";
                    if (txbISBN.Text.Length != 0)
                    {
                        iNr++; 
                        blnHasAnd = true;
                        if (iNr == 1)
                        {
                            strSEARCH += " WHERE ";
                            iNr++;
                        }
                        strSEARCH += " ISBN LIKE '" + txbISBN.Text + "%' ";
                    }
                    if ((blnHasAnd) && (txbEditor.Text.Length != 0)) strSEARCH += " AND ";
                    if (txbEditor.Text.Length != 0)
                    {
                        iNr++; 
                        blnHasAnd = true;
                        if (iNr == 1)
                        {
                            strSEARCH += " WHERE ";
                            iNr++;
                        }
                        strSEARCH += " Editor LIKE '" + txbEditor.Text + "%' ";
                    }
                    if ((blnHasAnd) && (txbEYear.Text.Length != 0)) strSEARCH += " AND ";
                    if (txbEYear.Text.Length != 0)
                    {
                        iNr++; 
                        blnHasAnd = true;
                        if (iNr == 1)
                        {
                            strSEARCH += " WHERE ";
                            iNr++;
                        }
                        strSEARCH += " EYear LIKE '" + txbEYear.Text + "%' ";
                    }
                    strSEARCH += " ORDER BY ID ASC, Author ASC;";  
                    try
                    {
                        OleDbDataAdapter adapter = new OleDbDataAdapter(strSEARCH, connOLEDB);
                        DataSet myDataSet;
                        myDataSet = new DataSet();
                        adapter.Fill(myDataSet, "TB_Book");
                        RowMax = myDataSet.Tables[0].Rows.Count;
                        RowCounter = 0;
                        listOfID.Clear();
                        for (int n = 0; n < RowMax; n++)
                        {
                            DataRow row0 = myDataSet.Tables[0].Rows[n];
                            DataColumn column0 = myDataSet.Tables[0].Columns["ID"];
                            listOfID.Add((row0[column0]).ToString());
                        }
                        myListBox.DataContext = myDataSet;
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message); 
                    }
                    finally
                    {
                        //connOLEDB.Close();
                    }
                    this.DetailWebPanel.Visibility = System.Windows.Visibility.Hidden;
                    this.insertDetailWebPanell.Visibility = System.Windows.Visibility.Hidden;
                    this.BookPannel.Visibility = System.Windows.Visibility.Visible;
                    this.InsertBookPanel.Visibility = System.Windows.Visibility.Hidden;  
                break;

                case "NEW":
                    try
                    {
                        Int32 iYear = Convert.ToInt32(txbEYear.Text);
                        transaction = connOLEDB.BeginTransaction(IsolationLevel.ReadCommitted);
                        cmdInsert.Transaction = transaction;
                        cmdInsert.Connection = connOLEDB; 
                        cmdInsert.CommandText = "INSERT INTO TB_Book (ID, Title, Author, ISBN, Editor, EYear) VALUES ('" + txbBID.Text + "', '" + txbTitle.Text + "', '" + txbAuthor.Text + "', '" +
                             txbISBN.Text + "', '" + txbEditor.Text + "', " + iYear + ");";
                        cmdInsert.CommandType = CommandType.Text;
                        cmdInsert.ExecuteNonQuery(); 
                        cmdInsert.CommandText = "Insert into TB_Website (URL, Description, Email, ID ) VALUES ('" + txbWURL.Text + "', '" + txbWDescription.Text + "', '" + txbWEmail.Text + "','" + txbWID.Text + "');";
                        cmdInsert.CommandType = CommandType.Text;
                        cmdInsert.ExecuteNonQuery(); 
                        transaction.Commit(); 
                        StatusMsg.Text = "Inserted !";
                        this.btnSave.Content = "Save";
                        this.btnSave.IsEnabled = false;
                        this.btnSave.Foreground = disableBrush;
                        this.btnUpdate.IsEnabled = false;
                        this.btnUpdate.Foreground = disableBrush;
                        this.btnDelete.IsEnabled = false;
                        this.btnDelete.Foreground = disableBrush;
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                        try
                        {
                            transaction.Rollback();
                        }
                        catch  {  }
                    }
                    finally
                    {
                        connOLEDB.Close();
                    } 
                    InsertBookPanel.Focus();
                    this.txbBID.Focus();
                    //http://www.meo-x.net
                break;

                case "UPDATE":
                    try
                    {
                        Int32 iYear = Convert.ToInt32(txbEYear.Text);
                        transaction = connOLEDB.BeginTransaction(IsolationLevel.ReadCommitted);
                        cmdUpdate.Transaction = transaction;
                        cmdUpdate.Connection = connOLEDB;
                        cmdUpdate.CommandText = "UPDATE TB_Book SET ID = '" + txbBID.Text + "', Title = '" + txbTitle.Text + "', Author = '" + txbAuthor.Text + "', ISBN = '" + txbISBN.Text + "', Editor = '" + txbEditor.Text + "',  EYear = " + iYear + " WHERE ID = '" + strID + "';";
                        cmdUpdate.CommandType = CommandType.Text;
                        cmdUpdate.ExecuteNonQuery();
                        cmdUpdate.CommandText = "UPDATE TB_Website SET URL = '" + txbWURL.Text + "', Description = '" + txbWDescription.Text + "', Email = '" + txbWEmail.Text + "', ID = '" + txbWID.Text + "' WHERE ID = '" + strID + "';";
                        cmdUpdate.CommandType = CommandType.Text;
                        cmdUpdate.ExecuteNonQuery(); 
                        transaction.Commit(); 
                        StatusMsg.Text = "Updated !";
                        this.btnSave.Content = "Save";
                        this.btnSave.IsEnabled = false;
                        this.btnSave.Foreground = disableBrush; 
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message); 
                        try
                        {
                            transaction.Rollback();
                        }
                        catch  { }
                    }
                    finally
                    {
                        connOLEDB.Close();
                    }
                    InsertBookPanel.Focus();
                    this.txbBID.Focus();
                break;

                case "DELETE":
                    cmdDelete.CommandText = "DELETE FROM TB_BOOK WHERE ID = '" + strID + "';";
                    MessageBoxResult msgResult = MessageBox.Show(cmdDelete.CommandText, "", MessageBoxButton.OKCancel, MessageBoxImage.Question);
                    if (msgResult.ToString() == "Cancel")
                    {
                        
                        break;
                    }
                    try
                    {
                        transaction = connOLEDB.BeginTransaction(IsolationLevel.ReadCommitted);
                        cmdDelete.Transaction = transaction;
                        cmdDelete.Connection = connOLEDB; 
                        cmdDelete.CommandType = CommandType.Text;
                        cmdDelete.ExecuteNonQuery();
                        cmdDelete.CommandText = "DELETE FROM TB_Website WHERE ID = '" + strID + "';";
                        cmdDelete.CommandType = CommandType.Text;
                        cmdDelete.ExecuteNonQuery(); 
                        transaction.Commit();
                        StatusMsg.Text = "Deleted !"; 
                        txbBID.Text = txbTitle.Text = txbAuthor.Text = txbISBN.Text = txbEditor.Text = txbEYear.Text = "";
                        this.btnDelete.IsEnabled = false;
                        this.btnDelete.Foreground = disableBrush;
                        this.btnUpdate.IsEnabled = false;
                        this.btnUpdate.Foreground = disableBrush;
                        this.btnSave.Content = "Save";
                        this.btnSave.IsEnabled = false;
                        this.btnSave.Foreground = disableBrush; 
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                        try
                        {
                            transaction.Rollback();
                        }
                        catch { }
                    }
                    finally
                    {
                        connOLEDB.Close();
                    }
                    txbBID.Text = txbTitle.Text = txbAuthor.Text = txbISBN.Text = txbEditor.Text = txbEYear.Text = ""; 
                    this.btnSave.IsEnabled = false;
                    this.btnSave.Foreground = disableBrush;
                    this.btnSave.FontWeight = FontWeights.Normal;  
                break;
            }
        }

    }
}

         
 
 
 
 
Didier Meo's ASP.NET web site  

 

 

Copyright © http://www.meo-x.net. ALL RIGHTS RESERVED