.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Home >> Articles >> WPF >> Post New Resource Bookmark and Share   

 Subscribe to Articles

CRUD Operation on XML DB in WPF Application

Posted By:Diptimaya Patra       Posted Date: March 14, 2010    Points: 25    Category: WPF    URL: http://www.dotnetspark.com  

CRUD Operation on XML DB in WPF Application. In this article we will see how to perform CRUD operation on an XML database in a WPF application.
 

Introduction

In this article we will see how to perform CRUD operation on an XML database in WPF.

CRUD1.gif

Creating WPF Application

Fire up Visual Studio and create a WPF Application, name it as CRUDXmlDbWPF.

We need to design for CRUD operation. I preferred Blend 3 and used Tab Control.

CRUD2.gif


CRUD3.gif

CRUD4.gif

XML Schema in C# Class

Create a class of your xml schema.

class Movies
{
        public string Name { get; set; }
        public string Genre { get; set; }
        public string Cast { get; set; }
        public string Year { get; set; }    
}


Global Variables

The following are the Global variables I have used.

ObservableCollection selectedList = new ObservableCollection();
List movieList;
List yearList;
Movies moviesDel; 

public Window1()
{
            InitializeComponent();
            btnUpdate.IsEnabled = false;
            btnDelete.IsEnabled = false;
            yearList = new List { "2010", "2009", "2008", "2007", "2006", "2005", "2004", "2003" };
            cmbYear.ItemsSource = yearList;
            cmbYearUpdate.ItemsSource = yearList;
            LoadData();        
}


Read Operation

We have an xml file named MovieDB.xml in the root directory. I have created a method to load data from the file.

#region Load Data
        void LoadData()
        {
            XDocument doc = XDocument.Load(@"E:\MovieDB.xml");
            movieList = (from movie in doc.Descendants("Movie")
                       orderby movie.Element("Name").Value
                       select new Movies
                       {
                           Name = movie.Element("Name").Value,
                           Genre = movie.Element("Genre").Value,
                           Year = movie.Element("Year").Value,
                           Cast = movie.Element("Cast").Value,
                       }).ToList(); 

            lbMovies.ItemsSource = movieList;
            ViewDataGrid.ItemsSource = movieList; 

        }       
 #endregion


Call the method whenever and wherever it is required to Load data.

Create and Update Operation

Create and Update operations are same except that we update an existing data in Update Operation.

So I have created a method called WriteToXml where I am writing to XML file depending on the Create or Update Operation.

#region WriteToXmlFile
        void WriteToXmlFile(Movies movies, bool isUpdate)
        {
            #region Add New
            if (!isUpdate)
            {
                FileStream fs = new FileStream(@"E:\MovieDB.xml", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(fs);
                fs.Close(); 

                XmlElement newMovie = xmlDoc.CreateElement("Movie");
                XmlElement name = xmlDoc.CreateElement("Name");
                name.InnerText = movies.Name;
                newMovie.AppendChild(name); 

                XmlElement genre = xmlDoc.CreateElement("Genre");
                genre.InnerText = movies.Genre;
                newMovie.AppendChild(genre); 

                XmlElement year = xmlDoc.CreateElement("Year");
                year.InnerText = movies.Year;
                newMovie.AppendChild(year); 

                XmlElement cast = xmlDoc.CreateElement("Cast");
                cast.InnerText = movies.Cast;
                newMovie.AppendChild(cast); 

                xmlDoc.DocumentElement.InsertAfter(newMovie,
                xmlDoc.DocumentElement.LastChild); 

                FileStream fsxml = new FileStream(@"E:\MovieDB.xml", FileMode.Truncate,
                                      FileAccess.Write,
                                      FileShare.ReadWrite); 

                xmlDoc.Save(fsxml);
                fsxml.Close();
            }
            #endregion 

            #region Update
            else
            {
                XDocument doc = XDocument.Load(@"E:\MovieDB.xml"); 

                foreach (var item in doc.Descendants("Movie"))
                {
                    if (item.Element("Name").Value == moviesDel.Name)
                    {
                        item.Element("Name").SetValue(movies.Name);
                        item.Element("Genre").SetValue(movies.Genre);
                        item.Element("Year").SetValue(movies.Year);
                        item.Element("Cast").SetValue(movies.Cast);
                        doc.Save(@"E:\MovieDB.xml");
                        break;
                    }
                }
            }
            #endregion 

        }         
#endregion


On Button Click events of Either Create or Update Operation you can call the above method.

#region Add Operation
        private void btnAdd_Click(object sender, RoutedEventArgs e)
        {
            string name = txtName.Text.Trim();
            string year;
            if (cmbYear.SelectedIndex != -1)
            {
                year = cmbYear.SelectedValue.ToString();
            }
            else
            {
                year = "2009";
            }
            string genre = txtGenre.Text.Trim();
            string cast = txtCast.Text.Trim();
 
            bool isUpdate = false; 

            if (name.Equals(string.Empty))
                name = "Un Named Movie";
            if (year.Equals(string.Empty))
                year = "2009";
            if (genre.Equals(string.Empty))
                genre = "No Genre";
            if (cast.Equals(string.Empty))
                cast = "No Cast"; 

            Movies newMovie = new Movies
            {
                Name = name,
                Year = year,
                Genre = genre,
                Cast = cast,
            }; 

            WriteToXmlFile(newMovie, isUpdate);
            txtName.Text = string.Empty;
            txtGenre.Text = string.Empty;
            txtCast.Text = string.Empty;
            cmbYear.SelectedIndex = -1;
            LoadData();
        } 
        #endregion 

        #region Update Operation
        private void btnUpdate_Click(object sender, RoutedEventArgs e)
        {
            if (lbMovies.SelectedIndex != -1)
            {
                string name = txtNameUpdate.Text;
                string year = cmbYearUpdate.SelectedValue.ToString();
                string genre = txtGenreUpdate.Text;
                string cast = txtCastUpdate.Text; 

                bool isUpdate = true; 

                if (name.Equals(string.Empty))
                    name = "Un Named Movie";
                if (year.Equals(string.Empty))
                    year = "2009";
                if (genre.Equals(string.Empty))
                    genre = "No Genre";
                if (cast.Equals(string.Empty))
                    cast = "No Cast"; 

                Movies updateMovie = new Movies
                {
                    Name = name,
                    Year = year,
                    Genre = genre,
                    Cast = cast,
                }; 

                WriteToXmlFile(updateMovie, isUpdate);
                lbMovies.SelectedIndex = -1;
                btnUpdate.IsEnabled = false;
                btnDelete.IsEnabled = false;
                LoadData();
            }
        }        
#endregion


On selection changed of the ListBox perform as below to bind data to the respective fields.

#region ListBox Selection Changed
        private void lbMovies_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            selectedList.Clear();
            if (this.lbMovies.SelectedItem is Movies)
            {
                selectedList.Add(((Movies)this.lbMovies.SelectedItem));
                moviesDel = (Movies)this.lbMovies.SelectedItem;
            }
            foreach (var item in selectedList)
            {
                txtNameUpdate.Text = item.Name;
                cmbYearUpdate.SelectedValue = item.Year;
                txtGenreUpdate.Text = item.Genre;
                txtCastUpdate.Text = item.Cast;
            }
            btnUpdate.IsEnabled = true;
            btnDelete.IsEnabled = true; 

        }         
#endregion


Delete Operation

On Delete button click event you can add the following code to perform the Delete Operation.

#region Delete Operation
        private void btnDelete_Click(object sender, RoutedEventArgs e)
        {
            if (moviesDel != null)
            {
                if (System.Windows.MessageBox.Show("Do you Really Want To Delete This Movie ?", "Delete Confirmation", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                {
                    XDocument doc = XDocument.Load(@"E:\MovieDB.xml"); 

                    foreach (var item in doc.Descendants("Movie"))
                    {
                        if (item.Element("Name").Value == moviesDel.Name)
                        {
                            ((XElement)item.Element("Name")).Parent.Remove();
                            doc.Save(@"E:\MovieDB.xml");
                            break;
                        }
                    }
                    LoadData();
                    moviesDel = null;
                    lbMovies.SelectedIndex = -1;
                    btnDelete.IsEnabled = false;
                }
                else
                {
                    moviesDel = null;
                    lbMovies.SelectedIndex = -1;
                    btnDelete.IsEnabled = false;
                }
            }
        } 
       #endregion


XAML Binding

The following code refers to XAML data binding and control's properties.





                        
                            
                            
                            
                            
                        



























That's it. Run your application and you would achieve the CRUD operation for XML data.

CRUD5.gif

CRUD6.gif


 Subscribe to Articles

     

Further Readings:

Responses

No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More Articles on C#, ASP.Net, Vb.Net, SQL Server and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend